Wednesday, May 20, 2009

Virtual function

A member function whose definition can be changed during run time is called virtual function. The definition can be changed using base class object pointer. According to the value of the address stored in the object pointer we can access the different virtual function definition in different derived classes.

general form is:

Class baseclass

{

---------

---------

Virtual returntype functionname( argrument_list)

{

--------------------

--------------------

}

};

Class derived : public baseclass

{

---------

---------

returntype functionname( argument_list)

{

-----------------------

-----------------------

}

};


Accessing the virtual function:

baseclass *ptr, obj1;
derivedclass obj2;
ptr = &obj1;
ptr->functionname(arguments);
ptr = &obj2;
ptr->functionname(arguments);

#include "iostream.h"

class figure
{
protected:
double x, y;
public:
void setdim(double i, double j)
{
x = i;
y = j;
}
virtual void showarea( )
{
cout << "No area computation defined "; cout << "for this class.\n"; } } ; class triangle : public figure { public: void showarea( ) { cout << "Triangle with height "; cout << p =" &t;">setdim(10.0, 5.0);
p->showarea();

p = &s;
p->setdim(10.0, 5.0);
p->showarea();

return 0;
}

No comments:

Post a Comment