Reputation: 75
What happens if a class has a "has-a" relationship with another class, and also it derives this same class?
class A
{
friend classB;
// here lots of things might be , but i just try to understand how should I think.
};
class B : public A
{
// here again might be couple lines of codes.
protected:
A d;
};
What is really going on here? How should I think about that?
Upvotes: 0
Views: 113
Reputation: 27611
I can't see why you would ever want to use 'friend' here. By stating in A that B is a friend class, you're saying that A trusts B to access its private members. However, B derives from A, so if you want to access members in A from B, but not allow anything else access, then those members just need to be 'protected', instead of 'private'.
Upvotes: 0
Reputation: 385174
Consider:
struct Human {};
struct Superhuman : Human
{
Human mentor;
};
Or perhaps a slightly less direct example:
struct Human
{
virtual ~Human() {}
};
struct Girl : Human
{
unique_ptr<Human> ptrToGirlfriendOrBoyfriend;
};
struct Boy : Human
{
unique_ptr<Human> ptrToGirlfriendOrBoyfriend;
};
(Replace unique_ptr
with shared_ptr
as necessary…)
So there are times when composing the same type used for inheritance does make sense, though I'd suggest that it's fairly rare.
Lose the friend
declaration, though, unless you really, really need it.
Upvotes: 0
Reputation: 129374
Nothing particularly special with this. You have a member variable of class A
called d
, and your class B
also contains everything that class A
contains, and anything extra added to it.
I can't really see much useful from this at a glance, but I'm sure there are circumstances when it may come in handy - having a pointer to an A object would make more sense, in that it would make it a linked list (or similar).
Upvotes: 1