Saturday, February 2, 2013

Virtual function in C++


Polymorphism:




Virtual Function:
In the case of inheritance, it makes right function call on the time. When the same function name is defined in both base and derived class, the function in base class is declared as virtual using the keyword virtual in the function such a function is called virtual function.
Ex:

class Base
{
 public:
  void display()
  {
   cout<<”display base function”;
  }
 virtual void show()
  {
   cout<<”show base function”;
  }
};

class Derived: public base
{
 public:
  void display()
  {
   cout<<”display derived function”;
  }
  void show()
  {
   cout<<”show derived function”;
  }
};

void main()
{
 Base *Ptr,b;
 Derived d;
 Ptr =&b;
 Ptr->show();//Base
 Ptr->display();//Base
 Ptr =&d;
 Ptr->show();//Derived
 Ptr->display();//Base
}

The rules for virtual function:
                                                       I.            The virtual function must be member function of some class.
                                                     II.            They are accessed by using object pointer.
                                                  III.            A virtual function can be a friend of another class.
                                                  IV.            We cannot have virtual constructor but we can have virtual destructor.
                                                    V.            If a virtual function is defined in the base class, it need not be necessary redefine in the derived class in such a case, base class function will be called.

0 comments:

Post a Comment

Powered by Blogger.