1

Isn't the friend function supposed to access everything that is in Base class and Derived class? class Derived: public Base -> everything that is in private in Base is now public inside the class derived.

class Base
{
private:
    int x;
};

class Derived : public Base
{
    int y;
public:
    void SetY(int value);
    void friend SetX(Derived &d);
};

void SetX(Derived &d)
{
    d.x = 100; // Why is this a problem?
               // Isn't Base supposed to be public now that is inherited?
}

int main()
{
    Derived d;
    SetX(d);
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
Tudor.Mano
  • 33
  • 5
  • 7
    *public Base -> everything that is in private in Base is now public inside the class derived.* That's not how it works. I suggested rereading how inheritance works in a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Mar 08 '18 at 21:21
  • Research what `protected` means. That should fix some misunderstandings you have of what `private` means. – Drew Dormann Mar 08 '18 at 21:33
  • If you want to access that `x` from the `Base` move your `friend` declaration into the `Base` and don't forget to forward declare `Derived` – Killzone Kid Mar 08 '18 at 22:25

2 Answers2

3

Your friend function void friend SetX(Derived &d); of Derived class is a friend function of that class only and it can only access private members of Derived class only but not allowed to access any private or protected member of a Base class. Also even from a Derieve class you can not access private members of a Base class but can access only the public and protected members. To reach/access the private members of a Base class you have to use public member function of base class.

There are two types of inheritance in C++

class B{};
class D:public B{};

All I mentioned above is applicable in the above case. Even though you inharite base B class as public to a Derieve class D all the private members inharites to Derieve D as private, protected members as protected and public as public.

But if you inharite as private like below all the members of Base class would be now private to the Derieve class.

  class B{};
  class D:private B{};

In this case a friend function can not even access any member of Base class B.

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
1

Isn't the friend function supposed to access everything that is in Base class and Derived class?

No. It is a friend of Derived, so it is supposed to access everything that the Derived class can access.

class Derived: public Base -> everything that is in private in Base is now public inside the class derived.

No. Everything that was private in Base before, is still private.

The use of public/protected/private for inheritance means something different than it does for member access control.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055