dimanche 24 février 2019

Get pointer to self inside class

How to get pointer to self object inside the class? Simple code below shows the creation of two objects: A and B. A contains pointer to B that must me assigned in B's constructor.

#include<iostream>

using namespace std;

class B;
class A {
    public:
    B* ptr;
};

class B {
    char array[1024];
    public:

    int value = 12;

    B() {};

    B(A* a) {
        a->ptr = this;
        cout << "constructor B addr = " << reinterpret_cast<std::uintptr_t>(this) << endl;
    }
};

int main() {
    B b;
    A a;

    b = B(&a);

    cout << "stack B addr       = " << reinterpret_cast<std::uintptr_t>(&b) << endl;

    a.ptr->value = 10;
    cout << "B.value            = " << b.value << endl;

    return 0;
};

Example output of this code seems to be logically incorrect:

constructor B addr = 140737243484752
stack B addr       = 140737243483712
B.value            = 12

So, is there any variant to get pointer to an object inside itself?

Aucun commentaire:

Enregistrer un commentaire