First of all, this code won't compile because you forgot the semi-colons after each member variable declaration and after MyItem
declaration and the keyword "struct" is typed wrong. Your code should look like this:
struct MyItem
{
var value;
MyItem* nextItem;
};
MyItem item = new MyItem;
Now answering your question, this code does not work because the new operator returns a pointer to the object created (a value of type MyItem*
) and you are trying to assign this pointer to a variable of type MyItem
. The compiler does not allow you to do this (because the value and the variable have different types). You should store the pointer into an apropriate variable, like this:
MyItem* item = new MyItem;
In this case, you must remember to delete item
to avoid memory leak once you no more need it.
Alternatively, you can create the object in the stack without the new
operator.
MyItem item;
In this case, the object ceases to exist when the function returns; you don't need to remember to delete it.