so in C++ you can instantiate objects using the new keyword or otherwise...
Object o = new Object();
but you can also just do
Object o = Object();
what exactly is the difference b/w the two and why would I use one over the other?
so in C++ you can instantiate objects using the new keyword or otherwise...
Object o = new Object();
but you can also just do
Object o = Object();
what exactly is the difference b/w the two and why would I use one over the other?
You can't do
Object o = new Object();
Thenew
operator returns a pointer to the type. It would have to beObject* o = new Object();
TheObject
instance will be on the heap.Object o = Object()
will create anObject
instance on the stack. My C++ is rusty, but I believe even though this naively looks like an creation followed by an assignment, it will actually be done as just a constructor call.The first type:
Will create a new object on the heap and assign the address to o. This only invokes the default constructor. You will have to manually release the memory associated with the object when done.
The second type:
Will create an object on the stack using the default constructor, then invoke the assignment constructor on o. Most compilers will eliminate the assignment call, but if you have (intended or otherwise) side-effects in the assignment operation, you should take that into account. The regular way to achieve creating a new object without invoking the assignment operation is:
I was Searching for a question like above but with variation, so I'll add my question here
I noticed difference in visual studio 2015 compiler and gcc v4.8.5.