4

This works:

MyObject *o;
o = new MyObject();

And this does not:

MyObject o = new MyObject();

Why?

Peter
  • 4,021
  • 5
  • 37
  • 58

3 Answers3

10

The keyword new returns a pointer. It must be assigned to a pointer of an object.

This would also work:

MyObject o = MyObject();

EDIT:

As Seth commented, the above is equivalent to:

MyObject o;

The default constructor (i.e. without parameters) is called if no constructor is given.

MPelletier
  • 16,256
  • 15
  • 86
  • 137
  • I see! I'm learning C++ after learning Java, so I was under the impression that `new` was required to instantiate an object. – Peter Apr 14 '12 at 19:53
  • 1
    @Peter, it is required only if you want a pointer. Using `new` allocates memory on the heap, rather than the program's stack. Think of it as the pointer points to something "outside your program". Something "new". – MPelletier Apr 14 '12 at 20:03
  • 1
    Actually `MyObject o = MyObject();` is not exactly equivalent to `MyObject o;` although the effect is the same; the former creates a temporary `MyObject` which is default-constructed, then uses the copy constructor to initialise `o` with the temporary, whereas the latter simply default-constructs `o` in-place. Without optimisations, the latter will be faster usually. – Seth Carnegie Apr 14 '12 at 20:05
  • 3
    @AndreasBrinck in C++ we change it to "You must `delete` what you `new`" – Seth Carnegie Apr 14 '12 at 20:06
  • @Seth Correct again, I took too great a shortcut on my explanation. – MPelletier Apr 14 '12 at 20:10
  • @SethCarnegie ...although, with newer C++ features, you shouldn't ever explicitly `delete`, rather upon `new`ing immediately assign to a `shared_ptr` or similar, and let that call `delete`. – Peter Wood Apr 14 '12 at 20:12
  • 1
    @PeterWood true, but that's not what Yoda says. (And btw, with even newer features, you shouldn't even use `new`, but `make_shared` and family.) – Seth Carnegie Apr 14 '12 at 20:13
5

Because they're not equivalent. Try:

 MyObject* o = new MyObject();
Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
4

new MyObject() returns a pointer to an object of type MyObject. So really you are trying to assign an object MyObject* (yes, a pointer can be considered an object, too). Thus, you have to declare a variable of MyObject* or something compatible like std::shared_ptr<MyObject>.

The proper initialisation is

// in C++03
MyObject* o(new MyObject());

// in C++11
MyObject* o {new MyObject()};

While the assignment

MyObject* o = new MyObject();

is valid as well.

bitmask
  • 32,434
  • 14
  • 99
  • 159