Name hiding

Suppose two subobjects named A and B both have a member name x. The member name x of subobject B hides the member name x of subobject A if A is a base class of B. The following example demonstrates this:

struct A {
   int x;
};

struct B: A {
   int x;
};

struct C: A, B {
   void f() { x = 0; }
};

int main() {
   C i;
   i.f();
}

The assignment x = 0 in function C::f() is not ambiguous because the declaration B::x has hidden A::x. However, the compiler will warn you that deriving C from A is redundant because you already have access to the subobject A through B.

A base class declaration can be hidden along one path in the inheritance graph and not hidden along another path. The following example demonstrates this:

struct A { int x; };
struct B { int y; };
struct C: A, virtual B { };
struct D: A, virtual B {
   int x;
   int y;
};
struct E: C, D { };

int main() {
   E e;
//   e.x = 1;
   e.y = 2;
}

The assignment e.x = 1 is ambiguous. The declaration D::x hides A::x along the path D::A::x, but it does not hide A::x along the path C::A::x. Therefore the variable x could refer to either D::x or A::x. The assignment e.y = 2 is not ambiguous. The declaration D::y hides B::y along both paths D::B::y and C::B::y because B is a virtual base class.



[ Top of Page | Previous Page | Next Page | Contents | Index ]