What is pure virtual function in C++?
A method inside a class having the signature but no body contents is called as pure virtual function. It is always overridden in child class.
Syntax
virtual <returntype> <functionname>(<argumentlist>)=0;
Such functions provide an abstraction layer to the business logic defined inside the function and also used to restrict access of specific function by an entity in some project.
Note:
A class having any pure virtual function is called as abstract class. Such classes are used for inheritance purpose only and cannot be instantiated.
Example
Create the classes to declare functionality different departments like Hr, Finance, Sales etc. for some organization to create an enterprise resource planning (ERP) software.
Hr --> salaryInfo()
Finance --> budgeting()
Sales --> forecasting()
Create the classes and instances in such a way that the departments can access only its own functionality
#include<iostream>
using namespace std;
class Hr
{
public:
virtual void salaryInfo()=0;
};
class Finance
{
public:
virtual void budgeting()=0;
};
class Sales
{
public:
virtual void forecasting()=0;
};
class Erp: public Hr,public Finance, public Sales
{
public:
void salaryInfo()
{
cout <<"Salary will be given on 7th of every month"<<endl;
}
void budgeting()
{
cout <<"Budget for 2020 will be 10 Cr" << endl;
}
void forecasting()
{
cout <<"Sale will be doubled this year" << endl;
}
};
main()
{
Hr *h=new Erp();
h->salaryInfo();
}
Output
Salary will be given on 7th of every month
Syntax
virtual <returntype> <functionname>(<argumentlist>)=0;
Such functions provide an abstraction layer to the business logic defined inside the function and also used to restrict access of specific function by an entity in some project.
Note:
A class having any pure virtual function is called as abstract class. Such classes are used for inheritance purpose only and cannot be instantiated.
Example
Create the classes to declare functionality different departments like Hr, Finance, Sales etc. for some organization to create an enterprise resource planning (ERP) software.
Hr --> salaryInfo()
Finance --> budgeting()
Sales --> forecasting()
Create the classes and instances in such a way that the departments can access only its own functionality
#include<iostream>
using namespace std;
class Hr
{
public:
virtual void salaryInfo()=0;
};
class Finance
{
public:
virtual void budgeting()=0;
};
class Sales
{
public:
virtual void forecasting()=0;
};
class Erp: public Hr,public Finance, public Sales
{
public:
void salaryInfo()
{
cout <<"Salary will be given on 7th of every month"<<endl;
}
void budgeting()
{
cout <<"Budget for 2020 will be 10 Cr" << endl;
}
void forecasting()
{
cout <<"Sale will be doubled this year" << endl;
}
};
main()
{
Hr *h=new Erp();
h->salaryInfo();
}
Output
Salary will be given on 7th of every month
Comments
Post a Comment