Polymorphism allows programmers to write programs that can automatically select a member function from a set of candidates. We've studied two of the requirements for polymorphism, inheritance and upcasting, in detail. Specifically, we've seen inheritance and casting effects on member variable access. Before exploring polymorphism, our only remaining task is understanding the effect of inheritance and casting on "regular" or non-polymorphic member functions. For clarity, let's remind ourselves that we are still not dealing with polymorphism but are examining how objects behave when casting is involved. The classes in our previous examples only contained member variables, but we now shift our focus to functions, and our examples reflect the shift.
class Parent
{
public:
void function1();
void function2();
};
class Child : public Parent
{
public:
void function1();
};
Member functions in an inheritance relationship.
Class Child inherits both functions defined in class Parent. However, the function1 defined in class Childoverrides the function1 defined in class Parent. Sometimes programmers will say that the Childfunction1, shadows, replaces, or hides the Parentfunction1. An instance of Child can still call the function1 with additional syntax.
The following code fragment demonstrates how upcasting affects function calls based on these two class specifications. Understanding which function runs in a given situation is crucial to understanding and effectively using polymorphism.
You must understand this behavior before you continue with the next section, where we take the final step and explore polymorphism.