Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

friend class : inherited classes are not friend as well?

Tags:

c++

class

friend

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 ?

like image 732
Jérôme Avatar asked Dec 05 '22 07:12

Jérôme


2 Answers

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.

like image 185
Martin York Avatar answered Dec 07 '22 21:12

Martin York


Friendship is not inherited, you have to explicitly declare every friend relationship. (See also "friendship isn't inherited, transitive, or reciprocal")

like image 35
sth Avatar answered Dec 07 '22 20:12

sth