C++: inheriting overloaded non-virtual method and virtual method both with the same name causes problem
Asked Answered
R

2

8

I am trying to inherit two equally named methods with different parameter lists to a derived class. One of them is virtual and overridden in the derived class, the other one is non-virtual. Doing so, i get a compile error while trying to access the non-virtual method of the base class from an derived class object.

Here is the code snippet

class Base {
public: 
    void f() {
        cout << "[Base::f()]" << endl;
    }

    virtual void f(int arg) {
        cout << "[Base::f(" << arg << ")]" << endl;
    }
};


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


int main() {
    Deriv d;
    d.f(-1);    
    d.f();  // <<-- compile error   
    return 0;
}

which produces the following compile error:

error: no matching function for call to ‘Deriv::f()’
note: candidates are: virtual void Deriv::f(int)

I am not an expert in C++, but until now I thought to be right in making the assumption that member methods can be completely distinguished by their signatures. Thus, the non-virtual method Base::f() should not be overridden and should remain accessible. Am I wrong with this?

Here are some interesting/additional comments on that:

    - the overriding method Deriv::f(int arg) could be non-virtual as well; the error occurs in either way
    - the error disappears/can be circumvented...
      ... by casting the Deriv object to the Base class
      ... when not overriding Base::f(int arg) in Deriv
      ... by adding the command "Base::f;" to the public part of Deriv

So, since I already know how to avoid this compile error, I am mainly interested in why this error happens!

Residency answered 4/8, 2010 at 14:26 Comment(3)
When you say "... by adding the command "Base::f;" to the public part of Deriv", you mean using Base::f;?Dentelle
possible duplicate of Overriding a Base's Overloaded Function in C++Cherokee
@Tomaka17: No, i mean exactly: put the line Base::f; to the class. But obviously this is the same as ths "using .." command.Residency
C
10

In Deriv, add this:

using Base::f;

In addition to the link given by @DumbCoder, you can find more details in my answer to a similar question: Overriding a Base's Overloaded Function in C++

Cherokee answered 4/8, 2010 at 14:31 Comment(1)
yeah, i already know this (see my comments below the code snippet). but why do have to add this and what does this do?Residency
I
2

Derived class function hides the base function defintion. Detailed explaination as to why and how

Impaction answered 4/8, 2010 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.