Virtual Function

  •  A virtual function is a member function that declared within a base class and redefined by a derived class.
  • Virtual function ensures that the correct function is called for an object.
  • They are mainly used to achieve runtime polymorphism.
  • Functions are declared with a virtual keyword with a base class are virtual function of base class version.
  • When there is a same name function in derived class as well as base class and we assign the base class pointer to address of derived class and when we call  that function with the base class pointer it executes base class function even it is pointing to the derived class, To to solve this problem a virtual function or you can say virtual keyword is used so, that base class function is overridden by the derived class function.

Rules for virtual functions

  1. virtual functions cannot be static.
  2. A virtual function can be a friend function of another class.
  3. Virtual function should be accessed using a pointer for reference of a base class.

// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;


class A{
    public:
    virtual void show(){
        cout<<"Class A";
    }
};

class B:public A{
    public:
    void show(){
        cout<<"Class B";
    }
};

int main() {
   A *a;
   B b;
   
   a = &b;
  a->show();
    return 0;
}


Post a Comment

Previous Post Next Post