Hi There!

I'm Dan Schlegel, an Associate Professor in the Computer Science Department at SUNY Oswego

Static vs. Dynamic Method Binding

A Motivating Example

Consider the following class hierarchy:

And, assume each class implements its own method called print_characteristics

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.

Output:

The Issue at Hand

If we add the following to main:

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:

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:

With no other changes, the output becomes: