Name Collisions and Inheritance

Like any other scope, a derived class can reuse a name defined in one of its direct or indirect base classes. As usual, names defined in an inner scope (e.g., a derived class) hide uses of that name in the outer scope (e.g., a base class) (§2.2.4, p. 48):

struct Base {    Base(): mem(0) { }protected:    int mem;};struct Derived : Base {    Derived(int i): mem(i) { } // initializes Derived::mem to i                               // Base::mem is default initialized    int get_mem() { return mem; }  // returns Derived::memprotected:    int mem;   // hides mem in the base};

The reference to mem inside get_mem is resolved to the name inside Derived. Were we to write

Derived d(42);cout << d.get_mem() << endl;       // ...

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.