I’m trying to understand the function of the “virtual” keyword in C++ – consider this example:
#ifdef USE_VIRTUAL
struct a {
virtual void say_hi() { std::cout << "hello from a" << std::endl; }
};
#else
struct a {
void say_hi() { std::cout << "hello from a" << std::endl; }
};
#endif
struct b : public a {
void say_hi() { std::cout << "hello from b" << std::endl; }
};
int main( int argc, char** argc )
{
a a_obj;
b b_obj;
a_obj.say_hi();
b_obj.say_hi();
}
This program outputs:
hello from a
hello from b
regardless of whether or not a::say_hi is declared as virtual or not. Since the function gets correctly overridden even when say_hi is not declared virtual, then what is the function of declaring it as virtual?
You aren’t using polymorphism. Polymorphic behaviour only affects pointers and references to base classes, like so:
Now accessing member functions of
a1,a2,a3is subject to polymorphism and virtual dispatch.However, you must declare the first function at the top of the inheritance hierarchy virtual, i.e. in
A! In your example, withoutvirtual, there’s no polymorphism and you always call the member function of the corresponding static type of the object. To test this, add another few lines: