In C++, I have a class A which is friend with a class B.
I looks like inherited classes of B are not friend of class A.
I this a limitation of C++ or my mistake ?
Here is an example. When compiling, I get an error on line "return new Memento":
Memento::Memento : impossible to access private member declared in Memento.
class Originator;
class Memento
{
friend class Originator;
Memento() {};
int m_Data;
public:
~Memento() {};
};
class Originator
{
public:
virtual Memento* createMemento() = 0;
};
class FooOriginator : public Originator
{
public:
Memento* createMemento()
{
return new Memento; // Impossible to access private member of Memento
}
};
void main()
{
FooOriginator MyOriginator;
MyOriginator.createMemento();
}
I could of course add FooOriginator as friend of Memento, but then, this means I would have to add all Originator-inherited classes as friend of Memento, which is something I'd like to avoid.
Any idea ?
See: Friend scope in C++
Voted exact duplicate.
I looks like inherited classes of B are not friend of class A.
Correct
I this a limitation of C++ or my mistake ?
It is the way C++ works. I don't see it as a limitation.
Friendship is not inherited, you have to explicitly declare every friend relationship. (See also "friendship isn't inherited, transitive, or reciprocal")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With