Reputation: 1603
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.
Upvotes: 0
Views: 302
Reputation: 29965
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.
Upvotes: 0
Reputation: 238321
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.
Upvotes: 1