Xpode.com        Click here to Print this article.

Virtual Functions II

Virtual Function

 The concept of virtual functions applies only if the base class and the derived class both contain function with the same prototype. But suppose we have the situation that the derived class contains such a function that is not present in the base class and we want to access that function using the base class pointer. It is not possible because there is no function in the base class with the same prototype otherwise we would have made that virtual. To make it possible we will have to use the concept of ‘Pure Virtual Function’. It is the function that does not have any body but we have to declare it in the base class so that we can access the derived class function with the pointer of the base class. This is shown in the following example:

class base
{
	public:
	void display( )		
	{
		cout<<"\nBase";
	}
};

class derived : public base
{
	public:
	void show( )
	{
		cout<<"\nDerived";
	}
};

void main( )
{
	base *ptr;	//Base class pointer ptr
	derived dobj;
	clrscr( );
	ptr=&dobj;	//ptr points to the object of derived class
        ptr->show( );	//Error as the base class does not contain 
a virtual show ( ) function. getch( ); }

To overcome it we will make a pure virtual function show ( ) in the base class and it will make the derived class show ( ) function accessible by the pointer of the base class. It is shown below:

class base
{
	public:
	virtual void show( )=0;	//Pure virtual function show( )
};

class derived : public base
{
	public:
	void show( )
	{
		cout<<"\nDerived";
	}
};	

void main( )
{
	base *ptr;	//Base class pointer ptr
	derived dobj;
	clrscr( );
	ptr=&dobj;	//ptr points to the object of derived class
        ptr->show( );	//Derived class function show( ) will be called.
	getch( );
}

First Page of Virtual Function >>



http://
http://

Contributed by:
Rohit kakria
I am software developer

Resourse address on xpode.com
http://www.xpode.com/Print.aspx?Articleid=140

Click here to go on website