public, private, and protected Inheritance

Access to a member that a class inherits is controlled by a combination of the access specifier for that member in the base class, and the access specifier in the derivation list of the derived class. As an example, consider the following hierarchy:

class Base {public:    void pub_mem();   // public memberprotected:    int prot_mem;     // protected memberprivate:    char priv_mem;    // private member};struct Pub_Derv : public Base {    // ok: derived classes can access protected members    int f() { return prot_mem; }    // error: private members are inaccessible to derived classes    char g() { return priv_mem; }};struct Priv_Derv : private Base {    // private derivation doesn't affect access in ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.