Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a pointer in c++

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.

like image 827
asaini007 Avatar asked Sep 21 '26 19:09

asaini007


1 Answers

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;
like image 128
Vlad from Moscow Avatar answered Sep 23 '26 08:09

Vlad from Moscow