C++ Class Polymorphism via virtual function

Introduction

It is said that the derived class is a base class.

Its type is compatible with the base class type.

Also, a pointer to a derived class is compatible with a pointer to the base class.

This is important, so let's repeat this: a pointer to a derived class is compatible with a pointer to a base class.

Together with inheritance, this is used to achieve the functionality known as polymorphism.

Polymorphism means the object can morph into different types.

Polymorphism in C++ is achieved through an interface known as virtual functions.

A virtual function is a function whose behavior can be overridden in subsequent derived classes.

And our pointer/object morphs into different types to invoke the appropriate function.

Example:

#include <iostream> 

class MyBaseClass 
{ 
public: //ww  w .  ja v  a  2s  .c o  m
    virtual void dowork() 
    { 
        std::cout << "Hello from a base class." << '\n'; 
    } 
}; 

class MyDerivedClass : public MyBaseClass 
{ 
public: 
    void dowork() 
    { 
        std::cout << "Hello from a derived class." << '\n'; 
    } 
}; 

int main() 
{ 
    MyBaseClass* o = new MyDerivedClass; 
    o->dowork(); 
    delete o; 
} 

In this example, we have a simple inheritance where MyDerivedClass is derived from MyBaseClass.

The MyBaseClass class has a function called dowork() with a virtual specifier.

Virtual means this function can be overridden in subsequent derived classes, and the appropriate version will be invoked through a polymorphic object.

The derived class has a function with the same name and same type of arguments in the derived class.

In our main program, we create an instance of a MyDerivedClass class through a base class pointer.

Using the arrow operator -> we invoke the appropriate version of the function.

Here the o object morphs into different types to invoke the appropriate function.

Here it invokes the derived version.

That is why the concept is called polymorphism.

If there were no dowork() function in the derived class, it would invoke the base class version:

#include <iostream> 

class MyBaseClass 
{ 
public: /*from w  w  w  . j  a va 2  s.  c  om*/
    virtual void dowork() 
    { 
        std::cout << "Hello from a base class." << '\n'; 
    } 
}; 

class MyDerivedClass : public MyBaseClass 
{ 
public: 

}; 

int main() 
{ 
    MyBaseClass* o = new MyDerivedClass; 
    o->dowork(); 
delete o; 
} 



PreviousNext

Related