0

As it is said - "friends are not inherited" .
it means that

class c
 {public:
 friend void i_am_friend();
 };

class d:public c
{public:
 //
};

here void i_am_friend() is not inherited in class d .In more technical terms(i think this way.)

Object of class d will not have memory allocated for void i_am_friend() as it is friend of base class .
Now consider question no. 14.3 at this page http://www.parashift.com/c++-faq/friends.html

class Base {
 public:
   friend void f(Base& b);
   ...
 protected:
   virtual void do_f();
   ...
 };

 inline void f(Base& b)
 {
   b.do_f();
 }

 class Derived : public Base {
 public:
   ...
 protected:
   virtual void do_f();  // "Override" the behavior of f(Base& b)
   ...
 };

 void userCode(Base& b)
 {
   f(b);
 }

How can this code be correct?? because

class derived d;// d will not have friend function
class base *b=&d; //as a result b also don't have member function

So call to f(b) should be error here.

So what is correct to say :-
friendship isn't inherited
or friendship is inherited but can't be used in derived class

1 Answer 1

2

friendship isn't inherited

This is true, even in your example. The call to f(b) should NOT be an error there, because the Derived object is converted into Base& type.

The function f can access only the private and protected parts of the Base class, but only public parts of the Derived class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.