Interchangeable objects with polymorphism (cont…)
•A function that calls a member function declared in a base class through a pointer or a reference to the base data type can call the version of the member function which is overriden in the derived class, if the method is tagged with the virtual keyword.
•
http://www.alessandroogheri.com
•//we assume here that the class Derived is derived from the class Base and that in the class Base there is the do_something_cool() member function declared
•void f(Base * bp) {
•bp->do_something_cool();
•}
•
•Derived D; Base B;
•f(&B); //legal: calls Base->do_something_cool()
•f(&D); //legal too : it calls Base->do_something_cool()
•       //if the method is not virtual,
•       //it calls Derived->do_something_cool() otherwise
In C++ object oriented programs, it is common to have some of the member functions of the base class tagged with the virtual keyword. If a member function is tagged as virtual, when the program must invoke it starting from a pointer or a reference to the base class , it detects at run-time if the pointer or reference is actually connected to an object of a derived class (which, as we have seen in the previous slide, is permitted), and if this is the case, it calls the proper version of the member function (and not the one declared in the base class). This mechanism, though, doesn’t happen if the virtual keyword is not present, in which case the compiler takes the decision of which version of the function must be invoked based on the information that it has at disposal at compile time, when it examines the line
bp->do_something_cool();
which, therefore, forces the invocation of the base class version.
Consider for example the following scenario: