Friend functions and classes work with virtual inheritance in a similar way as they do with non-virtual inheritance. However, there are a few nuances to be aware of.
Virtual inheritance is used to solve the diamond problem in multiple inheritance, ensuring that a base class is only inherited once, no matter how many times it appears in the inheritance hierarchy.
Consider a scenario where Base
is virtually inherited by both Derived1
and Derived2
, and MostDerived
inherits from both:
#include <iostream>
class Base {
public:
Base(int val) : value{val} {}
friend void showValue(Base &b);
protected:
int value;
};
void showValue(Base &b) {
std::cout << "Base value: " << b.value;
}
class Derived1 : virtual public Base {
public:
Derived1(int val) : Base{val} {}
};
class Derived2 : virtual public Base {
public:
Derived2(int val) : Base{val} {}
};
class MostDerived
: public Derived1, public Derived2 {
public:
MostDerived(int val)
: Base{val}, Derived1{val}, Derived2{val} {}
};
int main() {
MostDerived obj(42);
showValue(obj);
}
Base value: 42
In this example, showValue()
is a friend of Base
and can access its protected member value
. Since MostDerived
virtually inherits from Base
, showValue()
can access value
through the most derived object.
Friend functions and classes can work seamlessly with virtual inheritance, providing access to private and protected members of virtually inherited base classes.
Be mindful of the complexity virtual inheritance introduces and use friend declarations judiciously to maintain clean and understandable code.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the friend
keyword, which allows classes to give other objects and functions enhanced access to its members