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?
No, new and delete are not supported in C.
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.
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.
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.
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.
Since new
returns a pointer, you ought to use
Object *obj = new Object();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With