I have a question about inheritance and template methods. Suppose I have this two classes
class Base
{
public:
template<typename T>
void print(const T& s) {std::cout << "Base (templated) prints " << s << "\n";}
virtual void print(int i) {std::cout << "Base prints " << i << "\n";}
};
class Derived : public Base
{
public:
void print(int i) {std::cout << "Derived prints " << i << "\n";}
}
int main()
{
Derived d;
d.print(3); // works fine
std::string s = "hi";
d.print(s); // does not compile
return 0;
}
The compiler tells me ”no matching function for call to ‘Derived::print(std::string&)’’.
But Derived, inheriting from Base, should also allow a call to the template method print(..), no?
Things are also weird cause if I don’t define a method “print” in the derived class, then everything works fine and the compiler calls the base class template method.
Things work fine also if I define the template method also in the derived class, which calls the base class one, but that does not seem right to me…
Thanks for your help.
Declaring a function in the derived class hides any functions with the same name in the base class. You can unhide them with a using declaration: