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.
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.
I don't have a better answer than an anecdote: Not in my experience.
I recommend thinking about why you're going out of your way to avoid inheritance.