Friend vs Protected

Friend vs Protected

Sergey Abbakumov

It is interesting that protected in C++ gives access to fields or methods of the base class only for this, but friend does this for all instances:

class Base {
 protected:
  friend class Friend;
  int a_ = 0;
};

class Derived : public Base {
 public:
  Derived() {
    Base base;
    base.a_ = 0; // Error.
    a_ = 0; // No error.
  }
};

class Friend {
 public:
  Friend() {
    Base base;
    base.a_ = 0; // No error.
  }
};


Telegram channel: https://t.me/sea_plus_plus

Report Page