Search code examples
c++oopclassobjectnew-operator

What's the difference between new Object() and Object()


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 between the two, and why would I use one over the other?


Solution

  • You can't do Object o = new Object(); The new operator returns a pointer to the type. It would have to be Object* o = new Object(); The Object instance will be on the heap.

    Object o = Object() will create an Object 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.