When to allocate with new

Hey so I’ve been learning about stack and heap allocation and I understand when you allocate using new on the heap it is so the object can live past it’s scope. Now what I don’t understand is why you can’t just predefine the object in the header file (.h) so it can live past the scope anyways. Can someone please explain this to me, thank you :slight_smile:

I’m fairly new to UE4, but I’m confident with my C++. I’m writing a 2D game in UE4 and have not yet had to call the C++ “new” operator to allocation storage on the heap. I’m not even sure if it is common (some can correct here, as I would like to know …).

As actors are C++ classes, you define variables in the class header file and they keep their scope over the course of your actor until the actor is destroyed. Member functions can use these variables as well as define their own local variables. If you define a variable public in the class, then an actor that spawns this actor will have access to the variable as well. If you define an actor which inherits another actor then this actor can also access the protected members of the inherited actor.

As far as I know, you can use NewObject() to “create” an object in memory.

As for dynamic arrays of objects etc., you can use TArray<> and keep adding elements to it.

Hope this helps.

I didn’t get too deep into the topic, but as far as I know, the UObject class overloads the operator new, so using it can be difficult without knowing the details of the engine.

You mean global variables? Well, that’s a generally bad practice.

a.) globals are initialized before main starts.
What if one global variable depends on the other? Which one will be initialized sooner?

b.) hidden dependencies.
Function signature dont tell you that function use or not global variable. You need to know the implementation of the function to know that.
For example: GEngine. You have to check if (GEngine) ... every time before use, because you don’t know who, when and how modifies it.

c.) Multithreading … pain.

d.) Tests… pain.

e.) Linkage. Playing with extern or inline to make sure everything works as it should and the linker is happy.

The same problems apply to a singleton, which is also a global variable with only a “nicer” interface.