Home          welcome : Guest          Log In      
  Xpode.com Beta version

Click here to Search Article

Categories/Articles

 

Virtual Functions II

 

Submitted By:


Rohit kakria

Detail : I am software developer

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







Comments
Share this article   |    Print   
Guest      Wednesday, May 12, 2010
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 classgucci purses pandora pandora jewelry pandora beads pandora bracelet pandora charm bracelet
Guest      Wednesday, May 12, 2010
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 classlouis vuitton handbags authentic louis vuitton gucci sunglasses fake louis vuitton louis vuitton belts gucci handbags
 
*  Name         *   Comments :ar 8) :cry: 8)
:shock: :shock: :evil: :!:
:( :idea: :lol: :x
:green: :| :question: :P
:oops: :roll: :) :o
:twisted: :wink:
*  Email          
                          (will not publish)
     
  Location           
  Website            
Enter the code *
(as shown below)