0

Possible Duplicate:
C++: rationale behind hiding rule

In this code sample from http://www.gotw.ca/gotw/005.htm, I was shocked to learn that in class Derived, f(int) and f(double) are not visible!

class Base {
public:
    virtual void f( int ) {
        cout << "Base::f(int)" << endl;
    }

    virtual void f( double ) {
        cout << "Base::f(double)" << endl;
    }

    virtual void g( int i = 10 ) {
        cout << i << endl;
    }
};

class Derived: public Base {
public:
    void f( complex<double> ) {
        cout << "Derived::f(complex)" << endl;
    }

    void g( int i = 20 ) {
        cout << "Derived::g() " << i << endl;
    }
};

What is the reasoning behind this?

As I understand f( complex<double> ) has a different signature than the other two inherited versions of f().

  • Why are all three not visible in this scenario?
  • What are the ways to make sure the Base functions are visible in this case?
Community
  • 1
  • 1
Lazer
  • 90,700
  • 113
  • 281
  • 364

2 Answers2

2

1) Why are all three not visible in this scenario?

This is how name hiding works. Names in an inner scope hide all names from outer scopes (and this happens before overload resolution or anything else occurs).

2) What are the ways to make sure the Base functions are visible in this case?

Bring their names into the inner scope with using declarations (using Base::f;, using Base::g;), or change their names so that they are not hidden by the names in the derived class.

Mankarse
  • 39,818
  • 11
  • 97
  • 141
1

See http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9.

Essentially, Derived::f(complex<Double>) hides Base::f(int) and Base::f(double). You re-expose them by adding using Base::f to your definition of Derived.

The rationale for this is explained quite well in Item 33 of Effective C++.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680