Topic :Virtual Function in C++: Virtual Function | Pure Virtual Function.

Virtual Functions & Polymorphism:

Virtual Functions Belongs to the branch of Runtime Polymorphism in C++. We Already discussed about Polymorphism in our previous Tutorial.




image: Virtual function and Polymorphism

We Already discussed about Compile Time Polymorphism in our Polymorphism Tutorial. in this Tutorial we will discussed about Run-time Polymorphism:



Virtual Function:

A Virtual Function is a function that is Declared as Virtual in a base class and redefined in one or more derived classes. Thus, each derived class can have its own version of a Virtual Function.

If there are Member functions with same name in base class and derived class, Virtual Functions gives Programmer Capability to call member function of different class by a same function call depending upon different context. This feature in C++ Programming is known as Polymorphism which is one of the important feature of Object Oriented Programming. If a base Class and derived Class has same function and if we write code to access that function using pointer of base class then, The function in the base class is executed even, if the object of derived class is referenced with that pointer variable. This can be demonstrated by this Example:



/* Virtual Function Concept: InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class Base //Base Class:
{
    public:
        void display() //Simple function to display some content.
        {
            cout<<" Base Class "<<endl;
        }
};
 
class Derived: public Base //Derived class. Using Inheritance concept.
{
    public:
        void display() //redefine Same function.
        {
            cout<<" Derived Class "<<endl;
        }
};
 
main()
{
    Base *ptr; //pointer object of type Base.
    Derived obj; //object of type Derived
 
    ptr->display(); //function calling using Base-Class object:
 
    ptr=&obj; //pointer point to Address of Derived Class.
    ptr->display(); //function calling using pointer, that point to Derived class.
 
    return 0;
}


An Object (either Normal or Pointer) of derived class is type compatible with pointer to base class. so, ptr = &obj; is allowed in above Example.



In Above Example, even if the object of derived class Derived is put in pointer to Base Class, display() of the base class is executed. so in order to Execute the member function of Derived Class, we Need to use Virtual Keyword in the base class along with display() Function, which makes that function existing in appearance only but, we can't call that function. So let's try same example using Virtual Keyword.



/* Virtual Function: InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class Base //Base Class:
{
    public:
        virtual void display() //Virtual Function.
        {
            cout<<" Base Class "<<endl;
        }
};
 
class Derived: public Base //Derived class. Using Inheritance concept.
{
    public:
        void display() //redefine same Function.
        {
            cout<<" Derived Class "<<endl;
        }
};
 
main()
{
    Base *ptr; //pointer object of type Base.
    Derived obj; //object of type Derived
 
    ptr->display(); //function calling using Base-Class object:
 
    ptr=&obj; //pointer point to Address of Derived Class.
    ptr->display(); //function calling using pointer, that point to Derived class.
 
    return 0;
}


After the function of Base is made Virtual, code ptr->display() will call the display() of the derived class depending upon the content of pointer. in this example, display() function of two different classes are called with same code which is one of the example of Runtime Polymorphism in C++ Programming using Virtual function.



Pure Virtual Function:

Abstract class: An Abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one Pure Function.

In C++ Programming, sometimes inheritance is used only for the better visualization of data and we don't need to create any object of base class. For example: if we want to calculate area of different objects like Circle and Square then, we can inherit these classes from a shape, because it helps to visualize the problem but, we don't need to create any object of Shape. in such case, we can declare Shape as abstract class if we try to create object of a Abstract class, compiler shows error.

A pure Virtual function or abstract function in C++ is a virtual function for which we don't have implementation, we only declare it. If Expression =0 is added to a virtual function then, that function is becomes pure Virtual function.


Adding =0 to virtual function does not assign value, it simply indicates the virtual function is a pure function.


/*Abstract Class. (because of Pure virtual function)*/
class Base 
{
    public:
        void display(); //Not virtual function:
        virtual void display(); //virtual function but Not Pure:
        virtual void display()=0; //Pure Virtual function:
};


Here, Base is an Abstract class, because it has a pure Virtual function, so no objects of class Base can be directly created. Base is explicitly mean to be a base class. Let's have an complete example for Pure Virtual Function.



/* Pure Virtual Function example: InfoBrother:*/
 
#include <iostream>
using namespace std;
 
class Shape /* Abstract class */
{
   protected:
        float l;
 
   public:
        void get_data() /*this function is not virtual. */
        {
            cin>>l;
        }
 
        virtual float area() = 0; /* Pure virtual function */
};
 
 
class Square : public Shape //derived class.
{
   public:
        float area()
        { 
            return l*l; 
        }
};
 
 
class Circle : public Shape //derived class.
{
   public:
        float area()
        { 
            return 3.14*l*l; 
        }
};
 
int main()
{
   Square squ; //object of type Square:
   Circle cir; //Object of type Circle:
 
   cout<<"Enter length to calculate area of a square: ";
   squ.get_data();
   cout<<"Area of square: "<<squ.area();
 
   cout<<"\n\nEnter radius to calculate area of a circle:";
   cir.get_data();
   cout<<"Area of circle: "<<cir.area();
 
   return 0;
}


Virtual Function is used to support "Run Time Polymorphism", When a Base Class has a virtual member function, any class that inherits from the base class can redefine the function with exactly the same prototype. so When the virtual function is called by using a Base Class pointer, the compiler decides at Runtime which version of the function (i.e. Base Class version or Overridden Derived class version) is to be called and this phenomenon is known as "Runtime Polymorphism"







I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement