friendship not inheritable

H

Hicham Mouline

Hello,
A semi-skeptical colleague is asking me why friendship is not inheritable,
specifically:

class Base {
public:
virtual void f() const =0;
};

class Derived : public Base {
virtual void f() const { // impl };
};


class A {
friend void Base::f() const;
};


In the implementation of Derived::f() const,
it cannot access private members of A.
you have to actually make Derived::f() friend of A.

Is this part of the standard? Or is it unspecified?
Is the rationale explained somewhere?

PS: I tested this only with VS2005
regards,
 
M

Maxim Yegorushkin

Hello,
A semi-skeptical colleague is asking me why friendship is not inheritable,
specifically:

class Base {
public:
  virtual void f() const =0;

};

class Derived : public Base {
  virtual void f() const { // impl  };

};

class A {
  friend void Base::f() const;

};

Friendship derivation can be emulated:

class Base {
protected:
// Key is accessible by A and derived classes
enum Key { key };
friend class A;

public:
virtual void f(A*) const =0;

};

class A {
public:
// this function can only be invoked by users
// who have access to Base::Key
void foo(Base::Key);
};

class Derived : public Base {
virtual void f(A* a) const
{
a->foo(key);
}
};
 
H

Hicham Mouline

The suggestion would be to have protected or private friendship, depending
on "where"
in the class def the friend declaration was:

1)
class A {
protected:
friend void Base::f() const;
};
then Base::f() and all its overriding derived are friends,

2)
class A {
private:
friend void Base::f() const;
};

then just Base::f() is friend,
 
R

red floyd

Hello,
A semi-skeptical colleague is asking me why friendship is not inheritable,
specifically:

Think of it in terms of "real life", which in this case, C++ actually
mirrors.

Your friends' children are not necessarily your friends. And would
you want your friends' children playing with your private parts?
 
H

Hicham Mouline

:)
What about the posted suggestion though?

Hello,
A semi-skeptical colleague is asking me why friendship is not inheritable,
specifically:
Think of it in terms of "real life", which in this case, C++ actually
mirrors.
Your friends' children are not necessarily your friends. And would
you want your friends' children playing with your private parts?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,739
Latest member
Clint8040

Latest Threads

Top