A Motivating Example
Consider the following class hierarchy:
1 2 3 |
human robot \ / sentient_being |
And, assume each class implements its own method called print_characteristics
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include<iostream> using namespace std; class sentient_being { public: void print_characteristics(){ cout << "Sentient_being's print_characteristics" << endl; } }; class human : public sentient_being { public: void print_characteristics(){ cout << "Human's print_characteristics" << endl; } }; class robot : public sentient_being { public: void print_characteristics(){ cout << "Robot's print_characteristics" << endl; } }; |
If we define a main method which creates a sentient_being, human, and robot, then calls print_characteristics on each, it is clear what should happen.
1 2 3 4 5 6 7 8 9 10 11 |
int main() { sentient_being s; human h; robot r; s.print_characteristics(); h.print_characteristics(); r.print_characteristics(); return 0; } |
Output:
1 2 3 |
Sentient Being's print_characteristics Human's print_characteristics Robot's print_characteristics |
The Issue at Hand
If we add the following to main:
1 2 3 4 |
sentient_being *x = &h; sentient_being *y = &r; x->print_characteristics(); y->print_characteristics(); |
what should be the result of calling print_characteristics on x and y?
Two Options
1. Choose method to call based on variable type (static method binding)
2. Choose method to call based on object type (dynamic method binding)
Note: Option 2 is also known as dynamic dispatch and is a major topic in object oriented programming — subtype polymorphism.
C++ uses static method binding by default, so the output of the above additions is:
1 2 |
Sentient Being's print_characteristics Sentient Being's print_characteristics |
Other languages like Java use dynamic method binding by default. You may use dynamic method binding in C++ through the use of the virtual keyword. The important place to put this keyword in the above program is on sentient_being’s print_characteristics method:
1 2 3 4 5 6 |
class sentient_being { public: virtual void print_characteristics(){ cout << "Sentient_being's print_characteristics" << endl; } }; |
With no other changes, the output becomes:
1 2 |
Human's print_characteristics Robot's print_characteristics |