Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




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 >>

Share this article   |    Print    |    Article read by 3770 times
Author:
Rohit kakria
I am software developer
Related Articles: No related article
Related Interview Questions: No related interview question