-1

Having

  • a BASE class defining a virtual method
  • a DERIVED class which defines a virtual method with the same name, but different signature

the compiler complains that it cannot find the correct function in the BASE class when called from another class using a pointer to the DERIVED class.

Example (Constructors etc omitted):

class BASE {
    public: virtual int print(std::vector<double>& values);
};

int BASE::print(std::vector<double>& values){
    std::cout << "This is the base class!" << std::endl;
}
class DERIVED : public BASE {
    public: void virtual print(int a, int b);
};

void DERIVED::print(int a, int b){
    std::cout << "This is the derived class from int-method!" << std::endl;
}
class TEST {
    public: void testit();
};

void TEST::testit(){
    DERIVED derived;
    std::vector<double> a;
    derived.print(a);
}

The compiler complains with TEST.cpp:30:17: error: no matching function for call to ‘DERIVED::print(std::vector<double>&)

What can I do to overload virtual functions with different signatures in derived classes? For example, this may be useful to add functionality that cannot be available in the BASE class.

9

1 Answer 1

3

print in the DERIVED shadows print in the BASE, even though the signatures are different.

To fix, add using BASE::print; to the DERIVED. Note that this line can change the access modifier of the inherited function; if you want the function to be public, the using ... must also be public.

Be aware that you don't override any functions here (usually that's only possible if signatures are same). You create two unrelated functions with the same name. This means virtual can be removed, unless you plan to add more derived classes and actually override functions in them.

2
  • Thanks - got it! Adding public: using BASE::print; to the DERIVED class did the job! So what is the logics behind hiding/shadowing all methods of the BASE class when overloading these methods in a derived class? I assume there would be no ambiguity in not doing so ?!?
    – sputn1k
    Commented Oct 25, 2020 at 10:33
  • @sputn1k Probably that was done to make sure you can safely add new methods to a base class, without worrying about derived classes silently changing behavior if they has methods with the same name. Commented Oct 25, 2020 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.