Click here to Skip to main content
15,900,378 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here,

i am giving the example for virtual function .
C++
#include <iostream>
#include <vector>

class Account
{
public:
  
	virtual void PrintBalance()
	{
		std::cout<<"Base"<<std::endl;
	}
};

class SavingAccount
    : public Account
{
public:
   void PrintBalance()
   {
	   std::cout<<"SavingAccount"<<std::endl;
   }
};

class CurrentAccount : public Account
{
	public:
   void PrintBalance()
   {
	   std::cout<<"CurrentAccount"<<std::endl;
   }

};

int main()
{
	Account *pAccount=NULL;
	SavingAccount objsavingAccount;
	CurrentAccount objcurrentAccount;
	pAccount = &objsavingAccount;
	pAccount ->PrintBalance();

	pAccount = &objcurrentAccount;
	pAccount ->PrintBalance();

    return 0;
}



C++
OutPut:

SavingAccount
CurrentAccount



In Base class i am going to do the following changes,

class Account
{
public:

virtual void PrintBalance()=0;

};



still the output is same.

How exactly , can i differentiate between virtual function and pure virtual function.

regards
ranjith
Posted

The pure virtual function is meant to be derived, and cannot be instantiated.
That way you force someone using your API to derive that function to be able to use the API-

See also here.[^]
 
Share this answer
 
One difference between a pure virtual and a virtual function is that you are forced to implement all base class's pure virtual functions in your derived class to be able to create an object of this class.

I.e. if you do not implement the PrintBalance function in one of your derived classes, you will get an compilation error.

So pure virtual means that you have to implement the function for each derived class.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900