Tuesday, February 9, 2016

VIRTUAL FUNCTION

AIM:
         To implement a C++ program to illustrate virtual function
ALGORITHM:
Step 1: Include the header files
Step 2: Declare the base class base.

Step 3: Declare and define the virtual function show().
Step 4: Declare and define the function display().
Step 5: Create the derived class from the base class.
Step 6: Declare and define the functions display() and show().
Step 7: Create the base class object and pointer variable.
Step 8: Call the functions display() and show() using the base class object and pointer.
Step 9: Create the derived class object and call the functions display() and show() using the derived class object and pointer.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class base
{
    public:
      virtual void show()
      {
                cout<<"\n  Base class show:";
      }
      void display()
      {
              cout<<"\n  Base class display:" ;
      }
};
 class drive:public base
{
   public:
      void display()
      {
              cout<<"\n  Drive class display:";
      }
      void show()
      {
              cout<<"\n  Drive class show:";
      }
};
 void main()
{
   clrscr();
   base obj1;
   base *p;
   cout<<"\n\t P points to base:\n"  ;
    p=&obj1;
   p->display();
   p->show();

  cout<<"\n\n\t P points to drive:\n";
   drive obj2;
   p=&obj2;
p->display();
   p->show();
   getch();
}

SAMPLE OUTPUT:

              P points to Base

              Base class display
              Base class show

              P points to Drive

              Base class Display
              Drive class Show

RESULT:

                Thus a C++ program to illustrate virtual function is implemented successfully.

No comments:

Post a Comment