Wednesday, April 9, 2014

Virtual Functions and Run time Polymorphism

Before beginning this I would like to tell you one thing through the following
program:



// Virtual Functions and
// Run-time Polymorphism
#include <iostream.h>

// base class
class base
{
public:
int a;
};

// derived class
class derived:public base
{
public:
int b;
};

// main
void main()
{
base b;
derived d;

// base class pointer
base *bptr;

// pointer pointing
// to bases object
bptr=&b;

bptr->a=10;

// pointer pointing
// to deriveds object
bptr=&d;

// still is able to access
// the members of the base
// class
bptr->a=100;
}


The property above combined with virtual function can be used to achieve a
very special and powerful feature, known as run-time polymorphism.


We had discussed about What
is Polymorphism
before so we wont be discussing it here.


The program below illustrates how virtual functions can be used to achieve
run-time polymorphism.


Please read the code carefully so that you understand how it’s working.



// Using Virtual functions to
// achieve run-time Polymorphism
#include <iostream.h>

// base class
class base
{
public:
virtual void func()
{
cout<<"Bases func()
"
;
}
};

// derived class
class derived:public base
{
public:
void func()
{
cout<<"Deriveds func()
"
;
}
};

// main
void main()
{
int ch=0;

base b;
derived d;

// base class pointer
base *bptr;

while(ch!=3)
{
cout<<"1> Call Bases func
"
;
cout<<"2> Call Deriveds func
"
;
cout<<"3> Quit
"
;

cin>>ch;

switch(ch)
{
case 1:
// point to bases object
bptr=&b;
break;

case 2:
// point tp deriveds object
bptr=&d;
break;

default:
bptr=&b;
}

// call whichever function
// user has chosen to call
bptr->func();
}
}


Related Articles:




0 comments:

Post a Comment

 

Information Technology News Copyright © 2016 | Powered by Blogger