Pointer problem

Hello!
I followed this tutorial about C++ programming: “3rd Person Power-Up Game with C++”. I just don’t understand why I should use pointers when I create a class type variable like in the “Pickup.h”

UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Pickup", meta = (AllowPrivateAccess = "true"))
class UStaticMeshComponent* PickupMesh;

Can’t I just use like this?

UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Pickup", meta = (AllowPrivateAccess = "true"))
class UStaticMeshComponent PickupMesh;

And if not, why?

You use pointers because Unreal has a garbage collector. Unreal will sense when the PickupMesh is created / destroyed and take actions accordingly. It is the same reason that you spawn an actor instead of creating one with new. Unreal’s garbage collection is highly efficient so you need not worry.
Also from a memory perspective, having a pointer to an external class ( this is called assosciation), has less overhead than creating a member variable.
For eg : let’s say you a class like this :

class A
{
int i; 
float j;
}
class B
{
class A* a;
}

Now, B has a pointer so it’s data will be 4 bytes in size.
But suppose if you change the class to the following:

class B
{
A a;
}

Now B has an int and a float ( 8 bytes of data). This is just an example of a primitive class, imagine how much memory you would occupy when the class has huge data.

So basically I could use the “A a;” instead of “A* a;” but it would result a lots of unnecessary data in the memory, right?

If you can manage to compile successfully “A a” on UObjects and Actors then I’d be curious to know. :slight_smile: What I think ash9991win describes is the reasons why the engine is more likely to use pointers than member variables and the importance of the garbage collector in the whole process. But so far, all my tests in using non-pointers variables resulted in a compilation fail.

I see now. Many thanks to both of you! :slight_smile:

Yep…Unreal doesn’t let u create UObject as class members, only as pointers

Sure :slight_smile: Post any other questions if u have