c++ – Private inheritance

Question:

What is the purpose of inheritance with the access descriptor private, if all the fields of the base class become inaccessible?

Answer:

Precisely so that all members of the base class are not accessible from the outside (they are accessible only from within the class, or to friends of the class).

Inheritance is not much different from aggregation, and
class A : private B { ... }; similarly
class A { private: B b; };

One unlike private: B b; , when inheriting, functions B can be called as members of their class, i.e. not bf() but just f() .

You can also inherit from an abstract class, and override its methods without showing all these things to the outside, for example:

struct Callback { virtual void done() = 0; };

void run(Callback* b);

class Cls : private Callback {
public:
  void some() {
    run(this);
  }
private:
  void done() override { ... }
};
Scroll to Top