3

I always thought public methods of base class do get inherited by the derived class, even thought the derived class did not had definition of that particular method. For example

#include <iostream>

using namespace std;


    class A {
    public:
        int f() { cout << 3; return 0;}
        int f(int x) {cout << x; return 0;}
    }; 

    class B: public A {
    public:
        int f() {std::cout << 5; return 0;}

    };


    int main(){
       B ob;
       ob.f(7); 

       return 0;
    }

I was expecting the result to be : 7 , but I get compilation error saying

" error: too many arguments to function call, expected 0, have 1; did you mean 'A::f'?"

I know what the error is trying to say but I am little confused that the fuction from the Base class is not called.

pokche
  • 1,141
  • 12
  • 36

3 Answers3

7

Overloading a method in a derived class hides all base class versions.Even if the signature is different.If a method with the same name as in base class, exists in derived class then you won't be able to directly call base class versions.

You can do

  ob.A::f(7);
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
2

With your posted code, B::f shadows all versions of A::f. You can call A::f(int) from an object of type B by using couple of methods.

  1. Use A::f explicitly.

    B ob;
    ob.A::f(7); 
    
  2. Bring all versions of A::f into the scope of B.

    class B: public A {
       public:
          using A::f;
          int f() {std::cout << 5; return 0;}
    
    };
    

    Now you can use:

    B ob;
    ob.f(7); 
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

You can use another way:

class B: public A {
    public:
        using A::f;
        int f() {std::cout << 5; return 0;}

    };
Sumeet
  • 779
  • 6
  • 20