Name Hiding

last modified: February 13, 2001

Name hiding is a feature of C++. Quoting from C++ FAQs by Marshall P. Cline and Greg A. Lomow :

What is the hiding rule? A member of a derived class hides any member of a base class that has the same name as the derived class member.

Here's an example of the problem:

class Base
   {
   public:
   virtual void foo( int const & x ) { m_foo = x; },
   virtual int foo( void ) const { return m_foo; },

   private:
   int     m_foo;
   },;

class Derived : public Base
   {
   public:
   virtual void foo( int const & x ) { Base::foo( x ); DoFooChanged(); },
   void DoFooChanged( void ) {},
   },;

 Derived d;
 cout << d.foo();  // COMPILER ERROR int foo( void ) is hidden.

In post-standard C++ one would fix the problem with a using-declaration like:

class Derived : public Base
   {
   public:
   using Base::foo;
   // ... as before
   },;

This brings the foo of the base scope into the derived scope. In practice this is only a slight inconvenience in situations like this. -- DaveHarris


CategoryCpp


Loading...