Virtual-Function-in-C++ .

In this session i have discussed virtual function in C++ .


A virtual function is member function which is declared in base class and redefine(overriden) in derived class . We can achieve the run time polymorphism using virtual function .

Function overriding :

In function overriding the functions name same and arguments same but their behaviours differents . We use the virtual keyword . It is possible to redefine a function in derived class that has the same name , same argument and same return type in the base class .

Example : Write a program that demonstrate the virtual function .

    #include<iostream>
    using namespace std; 
    class Base
    { 
        public: 
        virtual void disp () 
        { 
            cout<<"disp() of Base class" <<endl;
        } 
        void show () 
        {
             cout<<"show() of Base class"<<endl;
        } 
    }; 
   
    class Derived : public Base
    { 
        public: 
        void disp ()  
        { 
            cout<<"disp() of Derived class"<<endl; 
        } 
   
        void show () 
        { 
            cout<<"show() of Derived class"<<endl; 
        } 
    }; 
   
    int main()  
    { 
        Base *bptr; 
        Derived d; 
        bptr = &d; 
       //virtual function, binded at runtime (Runtime polymorphism) 
        bptr->disp();  
       // Non-virtual function, binded at compile time 
        bptr->show();  
       return 0; 
    }
    
    OUTPUT : disp() of Derived class
             show() of Base class
    

Welcome to AndroidATPoint.

back image                     next image