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.

3
  • 3
    overloading a function in derived class hides all base class versions Commented Jun 14, 2016 at 4:57
  • Use virtual keyword in A Commented Jun 14, 2016 at 4:58
  • 1
    I found a link from stackoverflow - stackoverflow.com/questions/411103/… which explains the question lucidly. Commented Jun 14, 2016 at 5:01

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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); 
    

2 Comments

@ R Sahu ,but the above case works in Java.
@a874, I am not familiar with Java. I can't comment on that. However, that has nothing to do with whether it works in C++.
2

You can use another way:

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

    };

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.