0

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.

orematasaburo
  • 1,207
  • 10
  • 20
  • 1
    Note: `A::b.ptr` won't be pointing at `this` correctly when making copies/moves of `A` objects, since you didn't define copy/move constructors to assign `this` to `ptr` like you do in the default constructor. – Remy Lebeau Sep 02 '21 at 03:03
  • Could be a use case for _private_ inheritance. – Chad Sep 02 '21 at 03:56
  • There are several drawbacks, especially: default copy/move constructor/assignment are wrong. Might be useful though (parent/child relationship), but passing "parent" as argument of the function might be a good alternative. – Jarod42 Sep 02 '21 at 10:15

2 Answers2

1

My question is twofold: Should we avoid this kind of design?

Depends.

If you need it, then I see no reason to avoid it. If you don't need it but it's convenient and there's no significant cost, then I again see no reason to avoid it.

and is this design widely used in c++ programming?

I don't have a better answer than an anecdote: Not in my experience.

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

I recommend thinking about why you're going out of your way to avoid inheritance.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

Don't do this.

It will get out of sync if you copy A. It's also bad design that other coders won't understand immediately. Instead use inheritance. If you don't add any virtual functions, it won't have any overhead. It's also cleaner and everyone is familiar with it.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93