2 Polymorphism

A class is polymorphic if it inherits from a super class that has least one virtual method. A method of an object that is of a polymorphic class is associated with the object at run-time, rather than determined at compile time. Here is a quick example (in listing 1:


Listing 1:polymorphic
 
1class A 
2{ 
3  public
4    virtual void m1(void
5    { 
6      cout << ”A::m1” << endl; 
7    } 
8}
9 
10class B 
11{ 
12  public
13    virtual void m1(void
14    { 
15      cout << ”B::m1” << endl; 
16    } 
17}
18 
19void test(void
20{ 
21  B myB; 
22  A *pA; 
23 
24  pA = &myB; 
25  pA->m1(); 
26}

The output of the test subroutine is "B::m1" because even though pA is a pointer to a class A object, the class A object is a part of a class B object. Furthermore, method m1 is virtual and overriden in class B.

If you remove the virtual keywords, then the test subroutine prints A::m1 because without virtual, the method is selected at compile time based on the type of the pointer.