Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 386
Michael M. Adkins Avatar asked Jan 17 '11 19:01

Michael M. Adkins


People also ask

Does new keyword work in C?

No, new and delete are not supported in C.

Does C++ have a new keyword?

new keywordThe new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

What are valid C keywords?

Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier.

Which is not C keywords?

construct is not a keyword. All 32 Keywords are given for reference. auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while.


2 Answers

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.

like image 131
Andrey Avatar answered Sep 28 '22 10:09

Andrey


Since new returns a pointer, you ought to use

Object *obj = new Object();
like image 25
Federico klez Culloca Avatar answered Sep 28 '22 09:09

Federico klez Culloca