What is the difference between this:
Myclass *object = new Myclass();
and
Myclass object = new Myclass();
I have seen that a lot of C++ libraries like wxWidgets, OGRE etc use the first method... Why?
What is the difference between this:
Myclass *object = new Myclass();
and
Myclass object = new Myclass();
I have seen that a lot of C++ libraries like wxWidgets, OGRE etc use the first method... Why?
The new
operator returns a pointer to the object it creates, so the expression Myclass object = new Myclass();
is invalid.
Other languages don't have explicit pointers like C++ so you can write statements like Myclass object = new Myclass();
, but in C++ this is simply not possible. The return type of new Myclass();
is a pointer to a Myclass
object, i.e. Myclass *
.
The first example creates a pointer to MyClass and initializes it to point to the result of the new operator.
The second will likely not compile, as it is trying to create a MyClass object and assign it to a MyClass pointer. This could work in the unlikely event that you have a MyClass constructor that accepts a MyClass pointer.
The first is correct.
The second will generally not compile. And if it does compile then the class is doing some complicated things in a constructor/assignment operator. And it's probably leaking memory.
Myclass *object = new Myclass(); //object is on the heap
Myclass object; //object is on the stack
You create objects on the heap if you plan on using them throughout a long period of time and you create objects on the stack for a short lifetime (or scope).