Jérôme
Jérôme

Reputation: 27027

friend class : inherited classes are not friend as well?

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 ?

Upvotes: 4

Views: 14255

Answers (5)

Tanveer Badar
Tanveer Badar

Reputation: 5523

Friendship isn't transitive or inherited. After all, your friend's friend may not be your friend or your father's friends are not your friends in general.

Upvotes: 3

Loki Astari
Loki Astari

Reputation: 264471

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.

Upvotes: 7

Patrick
Patrick

Reputation: 8318

Friendship is not inherited, see http://www.cplusplus.com/doc/tutorial/inheritance.html, What is inherited from the base class?

Upvotes: 0

Kosi2801
Kosi2801

Reputation: 23115

The friend directive was originally intended as some "loophole" to bypass the encapsulation mechanism.

With friend you have to specify exactly(!), which classes are your friend. The friendship is not inherited and so FooOriginator has no access to Memento in your example.

But ideally, before you're thinking how to solve your problem with the friend directive, I'd suggest to have a look at your design in general and try to get rid of the need to use friend as it could be seen to live in the same category as our loved goto :)

Upvotes: 0

sth
sth

Reputation: 229633

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

Upvotes: 6

Related Questions