mercredi 1 septembre 2021

Should we avoid letting member variables to have "this" pointer

In c++, one can let member variable to have this pointer. In the following example, instance b of class B is a member variable of class A, and b has "this" pointer of class A as a member variable.

My question is twofold: Should we avoid this kind of design? and is this design widely used in c++ programming?

class A;
struct B
{
  A* ptr;
};

class A
{
  public:
    A() : b(B{this}) {};
    B b;
};

int main(){
  auto a = A();
}

The motivation of this kind of design is that, I want to use many variables and class methods of A without inheritance.

Aucun commentaire:

Enregistrer un commentaire