In this code, I have defined three structs, base
, derived
and MoreDerived
each inheriting from the previous member in the list.
However, I have defined the function f()
to be virtual in the derived
struct, NOT in the base struct.
#include <iostream>
struct base {
void f() {
std::cout << "base\n";
}
};
struct derived : base {
virtual void f() {
std::cout << "derived\n";
}
};
struct morederived : derived {
void f() {
std::cout << "more derived\n";
}
};
int main()
{
derived d;
morederived md;
base* dp = &d;
base* mdp = &md;
dp->f();
mdp->f();
}
The code above prints base \n base
as expected. And if I declare dp
and mdp
to be pointers of type derived*
, the code prints derived \n more derived
as expected again, since f
is defined to be virtual in the derived.
Of course, this code is small and so the results are predictable. But in large code bases, is doing the above ever a good idea?
Note: I have not seen this in any codes yet, in my limited c++ experience, nor do I have any plans to use such a pattern (or anti-pattern :-D). I am asking this purely out of curiosity.
EDIT: I don't feel this question is not a duplicate to the one pointed out. I am not asking if the virtual keyword is necessary in a derived class. I am asking the effects/plusses/minuses of placing the virtual keyword on a function f()
that has an implementation in the base class, but is declared virtual only in the derived class, and then is inherited by other classes.
Specifically I am asking if this thing is a patter or anti-pattern.