Michael M. Adkins
Michael M. Adkins

Reputation: 175

What's wrong with the "new" keyword in C++?

I know that this might sound like a stupid question, but why do I get an error which says something like "

cannot convert Object* to Object

" when I try to instantiate a new Object by using the statement "

Object obj = new Object();

"?

Am I to understand that the "new" keyword is reserved for pointers? Or is it something else?

Upvotes: 5

Views: 3987

Answers (6)

Bram
Bram

Reputation: 765

the new operator makes a pointer to a object

there for Object *obj = new Object() should work.

but just Object obj() constructs the object just fine but in stack space

Upvotes: 6

Ahsan Fayaz
Ahsan Fayaz

Reputation: 245

I would have simply left a comment, but apparently I need a certain rep to do so.

In Java, variables used to store Objects are implicitly pointers to the Object. So new works the same way in C++ as Java, but you're not made aware of it in Java. I am going to guess that's the reason for your confusion.

Upvotes: 1

Richard Pennington
Richard Pennington

Reputation: 19975

Object obj;

is all you need. It creates the object obj.

Upvotes: 6

Federico klez Culloca
Federico klez Culloca

Reputation: 27149

Since new returns a pointer, you ought to use

Object *obj = new Object();

Upvotes: 8

Hilydrow
Hilydrow

Reputation: 918

Exactly. New creates an object on the heap, and returns a pointer to it.

Upvotes: 6

Andrey
Andrey

Reputation: 60105

Object* obj = new Object();

new always return pointer to object.

if you write just Object obj it means that obj will hold the object itself. If it is declared this way inside function then memory will be allocated on stack and will be wiped once you leave that function. new allocates memory on heap, so the pointer can be returned from function. Note that pointer can also point to local (stack) variable also.

Upvotes: 40

Related Questions