Peter
Peter

Reputation: 4141

C++ Pointers and Object Instantiation

This works:

MyObject *o;
o = new MyObject();

And this does not:

MyObject o = new MyObject();

Why?

Upvotes: 5

Views: 10856

Answers (3)

MPelletier
MPelletier

Reputation: 16677

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.

Upvotes: 11

bitmask
bitmask

Reputation: 34628

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.

Upvotes: 4

Andreas Brinck
Andreas Brinck

Reputation: 52519

Because they're not equivalent. Try:

 MyObject* o = new MyObject();

Upvotes: 5

Related Questions