Inheritance/Polymorphism  «Prev  Next»
Lesson 11 Virtual functions
Objective Virtual function selection

Add a virtual function to the shape class that returns the name of a shape as a char* value.


Virtual Function
An ordinary virtual function must be executable code. When invoked, its semantics are the same as those of other functions. In a derived class, it can be overridden, and the function prototype of the derived function must have matching signature and return type.
This is in contrast to an overloaded member function, which is compile-time selected based on its signature. An overloaded member function can have distinct return types.
The selection of which function definition to invoke for a virtual function is dynamic. The typical case occurs when a base class has a virtual function and derived classes have their versions of this function. A pointer to a base class can point at either a base class object or a derived class object. The member function selected will depend on the class of the object being pointed at, not on the pointer type.
In the absence of a derived type member, the base class virtual function is used by default. Also, once declared virtual, this property is carried along to all redefinitions in derived classes. It is unnecessary in the derived class to use the function modifier virtual.

Consider the following example:
//virtual function selection.
class B {
public:
   int  i;
   virtual void  print_i() const
     { cout << i << " inside B" << endl; }
};

class D : public B {
public:
   //virtual as well
   void  print_i() const
     { cout << i << " inside D" << endl; }
};

int main()
{
   B   b;
   B*  pb = &b;              //points at a B object
   D   f;
    
   f.i = 1 + (b.i = 1);
   pb -> print_i();          //call B::print_i()
   pb = &f;                  //points at a D object
   pb -> print_i();          //call D::print_i()
}

The output from this program is
1 inside B
2 inside D

Virtual Exercise - Exercise

Click the Exercise link to add a virtual function to the shape class that returns the name of a shape as a char* value.
Virtual Exercise - Exercise