简体   繁体   中英

Make a pointer to an object in the constructor C++

I would like to know how to make a pointer to a newly created object in the constructor in c++?

What is the address of a class?

class MyClass
{
    public:
};

class MyClass2
{
    public:
    //I need a pointer to the created object
    MyClass2 *pObjectName;

    //Constructor
    MyClass2()
    {
        pObjectName = &//I have no clue how to get the adress of the (not yet) created object.
    }
};

int main()
{
    //The way it works
    //Makes Object
    MyClass *pObject;
    MyClass Object;
    //pObject points to Object
    pObject = &Object;
    //Prints adress of Object
    printf("%p", pObject);


    //The way I would like to see it work
    MyClass2 Object2;
    //Prints adress of Object
    printf("%p", Object2.pObjectName);

}

It would be:

MyClass2()
{
    pObjectName = this;
}

But you do not need to do that. A this pointer is implicitly passed to each non-static member function of a class.

Inside the class you can access the pointer to the object with this . This pointer is defined and passed implicitly inside every instance method. Therefore you don't really need to memorize it into another variable.

you need to use this , eg:

MyClass2()
{
  pObjectName = this;
}

Why not say:

MyClass object;
printf("%p", &object);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM