c++ virtual keyword vs overriding function
Consider the following example. The important line to illustrate the need for virtual
and override
is c->printMe();
. Note that the type of c
is Base*
, however due to polymorphism it is correctly able to call the overridden method from the derived class. The override
keyword allows the compiler to enforce that a derived class method matches the signature of a base class's method that is marked virtual
. If the override
keyword is added to a derived class function, that function does not also need the virtual
keyword in the derived class as the virtual is implied.
#include <iostream>
class Base{
public:
virtual void printMe(){
std::cout << "I am the base" << std::endl;
}
};
class Derived: public Base{
public:
void printMe() override {
std::cout << "I am the derived" << std::endl;
}
};
int main() {
Base a;
Derived b;
a.printMe();
b.printMe();
Base* c = &b;
c->printMe();
return 0;
}
The output is
I am the base
I am the derived
I am the derived
With the code you have, if you do this
Derived derived;
Base* base_ptr = &derived;
base_ptr->printMe();
What do you think happens? It will not print out I am the derived
because the method is not virtual, and the dispatch is done off the static type of the calling object (i.e. Base
). If you change it to virtual the method that is called will depend on the dynamic type of the object and not the static type.