1

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);

}
0

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

you need to use this, e.g:

MyClass2()
{
  pObjectName = this;
}

Comments

0

Why not say:

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

2 Comments

Because I won't use it for just the printf function ;). Thanks alot though!
I don't understand what you are trying to achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.