Different methods for instantiating an object in C++


What is the difference between this:

Myclass *object = new Myclass();


Myclass object = new Myclass();

I have seen that a lot of C++ libraries like wxWidgets, OGRE etc use the first method... Why?

3/24/2009 2:33:43 PM

Accepted Answer

The second is wrong !

You may use

MyClass object;

That will work.

Now, concerning how to choose between these two possibilities, it mainly depends on how long your object should live. See there for a thorough answer.

5/23/2017 12:02:56 PM

Myclass *object = new Myclass(); //object has dynamic storage duration (usually is on the heap)
Myclass object; //object has automatic storage duration (usually is on the stack)

You create objects with dynamic storage duration (usually on the heap) if you plan on using them throughout a long period of time and you create objects with automatic storage duration (usually on the stack) for a short lifetime (or scope).

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow