Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • VIRTUAL FUNCTIONS IN C++

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 299
    Comment on it

    Virtual function is a member function  in base class, which is redefined in the derived class.

    Virtual function is declared by using the keyword virtual.

    Syntax of virtual function:

    class main_Class  // denotes the base class of virtual function 
    {
    public:
       virtual void pure_virtual() = 0;  // denotes a pure virtual function in c++
       // note that there is no function body	 
    };
    
    

    By using declaresdisplay() in parent class, we can generate the appearance of that function but it can't be called.

    For making the function virtual , we have to add the virtual keyword before the function.

    Virtual function resolves at run-time(dynamic binding).

     

    E.g of virtual function:-

    class Base
    {
     public:
     virtual void show()
     {
      cout << "Base class";
     }
    };
    class Derived:public Base
    {
     public:
     void show()
     {
      cout << "Derived Class";
     }
    }
    
    int main()
    {
     Base* a;       //Base class pointer
     Derived b;     //Derived class object
     a = &b;
     a->show();     //Late Binding Ocuurs
    }

    In above code the dynamic binding will occur because virtual keyword is used before the base class, so derived version of function will be called. So the output will be:

    Output : Derived class

     

    E.g without using the virtual keyword:-

    class Base
    {
     public:
     void show()
     {
      cout << "Base class";
     }
    };
    class Derived:public Base
    {
     public:
     void show()
     {
      cout << "Derived Class";
     }
    }
    
    int main()
    {
     Base* a;       //Base class pointer
     Derived b;     //Derived class object
     a = &b;
     a->show();     //Early Binding Ocuurs
    }

     

    When using the base class pointer, it will always call the base version of the function.

    so output will be:

    Output : Base class

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: