Having
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.
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.