I'm starting to learn C++ and about pointers. However I'm a little confused in their initialization. From what I understand, if I have some class X, the following code is valid:
X* pointer = new X();
This confuses me because I'd expect you'd want to initialize a pointer by giving it the address of an object, as opposed to the object itself, as in:
X* pointer = &(new X());
Does C++ automatically covert the former to the latter? Thanks.
Operator new returns the address of the created object. It does not return the object itself.
Also you could use a reference to the created object. For example
X &x = *( new X() );
//...
delete &x;
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