Lab Sheet 7

Lab Sheet 7 

Understanding the Concept of Virtual Function, Virtual Base Class, and RTTI


Virtual Function

The overridden function in the derived class can be invoked by means of a base class pointer if the function is declared virtual in the base class. Suppose a virtual function get() is defined in the base class Base and again it is defined in the derived class Derived.

We can use the base class pointer to invoke the function get() of the derived class.

Derived d;

Base *b;

b=&d;

b->get(); //calls get() of the derived class.

 

Virtual Destructors

When a base class pointer that is pointing to a derived class object is deleted, the destructor of the derived class, as well as destructors of all its base classes, is invoked, if the destructor in the base class is declared as virtual.

 

Virtual Base Class

Consider inheritance of the following type.

This type of inheritance is also called multipath inheritance as the Child gets the properties of G-Parent through two paths, Parent-1 and Parent-2. In this type of inheritance, there may be ambiguity in the members of the derived class child because it is derived from two base classes, which are again derived from the same base class. Hence to avoid this ambiguity the class G-Parent can be made virtual.

 

Runtime Type Information (RTTI)

The runtime type information is one of the features of C++ that exhibit runtime polymorphic behavior. In C++ we can find the type information of an object at runtime and change the type of the object at runtime. The operators dynamic_cast and typeid are used for runtime type information.

For example, if Animal is a polymorphic base class and Dog and Cat are derived classes of base class Animal then

Animal *anmp;

Dog dg;

Cat ct;

anmp=&dg;

cout<< typeid(*anmp).name();

displays the information of the object pointed by anm pointer.

Similarly,

Cat *cpt;

cpt=dynamic_cast<Cat*>(panm);

The downcast is successful if panm is holding the address of objects of class Cat.


Exercises