Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Hiding inherited names


Take a look at this program:

// For exercise.
// We override one of the overloads in class B. 
// Is the other - vf(double) -  inherited?

#include <iostream>
#include <string>

using namespace std;

class A {
private:
   double a;
public:
  virtual void vf(double d){                // Virtual vf(double)
    cout << "virtual vf(double) in A: " 
         << d << endl;
  }

  virtual void vf(){                        // Virtual vf()
    cout << "virtual vf() in A" 
         << endl;
  }

};

class B : public A {
private:
  double b;
public:

  void vf() override {                      // Virtual vf() overrides A::virtual vf()
    cout << "virtual vf() in B" << endl;
  }

                                            // It is expected that A::vf(double) is inherited.
                                            // BUT THERE ARE PROBLEMS - COMPILER ERROR.
};


int main(){
  B *b = new B();
  
  b->vf();
  b->vf(5.0);                               // Compiler error:  no matching function for call to B::vf(double)
}

The function vf() in B, which overrides vf() from B, happens to hide the inherited vf(double) from A.

You may override vf(double) in B as well, but this is not really what we want. We want that the inherited A::vf(double) to be visible in B. The following trick will do it:

#include <iostream>
#include <string>

using namespace std;

class A {
private:
   double a;
public:
  virtual void vf(double d){                // Virtual vf(double)
    cout << "virtual vf(double) in A: " 
         << d << endl;
  }

  virtual void vf(){                        // Virtual vf()
    cout << "virtual vf() in A" 
         << endl;
  }

};

class B : public A {
private:
  double b;
public:
  using A::vf;                              // vf from A is now available in B.

  void vf() override {                      // Virtual vf() overrides A::virtual vf()
    cout << "virtual vf() in B" << endl;
  }

                                            // It is expected that A::vf(double) is inherited.
                                            // And indeed, it is in this version.
}; 


int main(){
  B *b = new B();
  
  b->vf();
  b->vf(5.0);                               // Compiles in this version.
}


You should pay attention to the using declaration using A::vf added to the public part of B. This makes all vf names from A usable in B.