Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointers and Object Instantiation

This works:

MyObject *o;
o = new MyObject();

And this does not:

MyObject o = new MyObject();

Why?

like image 220
Peter Avatar asked Dec 01 '22 00:12

Peter


2 Answers

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.

like image 119
MPelletier Avatar answered Dec 05 '22 06:12

MPelletier


Because they're not equivalent. Try:

 MyObject* o = new MyObject();
like image 34
Andreas Brinck Avatar answered Dec 05 '22 06:12

Andreas Brinck