Wednesday, August 7, 2013

VIRTUAL FUNCTION - c++


VIRTUAL FUNCTION :- 

Virtual Function is a function that is declared within a base class and redefined in the derived class. Virtual functions are declared by preceding the class declaration with a keyword "virtual". When a virtual function is declared C++ decides to execute a function based on the type of object pointed by the base pointer and not on the type of pointer.
Example:
#include <iostream.h>
#include<conio.h>
#include<stdio.h>
class BB
  {
    public:
       void  show() { cout  << " BASE BASE\n" ; }
       virtual void print() { cout << "base base\n"; }
  };
class DD : public BB
  {
    public:
      void show() { cout << "DERIVED DERIVED\n"; }
      void print() { cout << "derived derived\n"; }
  };
int main()
  {
    
     BB B;
     DD D;
     BB *ptr;
    
     cout << "ptr points to base class\n" ;
     ptr =  &B;
     ptr->show();
     ptr->print();
  
     cout << "ptr points derived class\n";
     ptr = &D;
     ptr->show();
     ptr->print();
     getch();
     return 0;
  }

OUTPUT:
ptr points to base class
BASE BASE
base base
ptr points derived class
BASE BASE
derived derived