Pure Virtual Functions
And to represent it correctly we need to code it like below:
}
Abstract Classes
Example:
We cannot create objects of the base class with a pure virtual function.
· As creating an object under base class will generate a Compile Time Error.
· Base class with Pure virtual function are called abstract classes.
· Abstract class cannot be instantiated, but pointers and references of abstract class type can be created
· Pure virtual functions are simply represented by the blank virtual function in the base class which does not have any body.
· Virtual member function without definition is called pure virtual function.
And to represent it correctly we need to code it like below:
//Base Class
class Cars {
public:
virtual void SetPower()= 0;
}
· They specify that the derived classes define that function on their own. Thus we replace their definition with 0.
· Each derived class inheriting from the base class with a pure virtual function must override that function.
Abstract Classes
· And when we declare a Base class function as Pure Virtual Function, that means the Base class is now called as Abstract Class which is different from the concept of data abstraction.
· Abstract classes are used to create pointers and take advantage of its polymorphic abilities.
Example:
#include <iostream>
using namespace std;
//Abstract Base Class
class Base {
public:
virtual void Display()= 0; //Pure virtual Function
};
//Derived Class
class Derived:public Base
{
public:
void Display(){
cout<<"It override the pure virtual function of base class"<<endl; //it will be in the Console or output screen
}
};
int main() {
// Base b; Generate a Compile Time Error as the base class is an abstract class and thus commented
Base *b; //instead of creating an object, we use a pointer
Derived d; //We can created an object for derived classes though
b=&d; //Pointer b is now addressed to derived class d object
b->Display(); //Then it will call the function using arrow selection operator
return 0;
}
/*
Output:
It override the pure virtual function of base class
*/
· As creating an object under base class will generate a Compile Time Error.
· Base class with Pure virtual function are called abstract classes.
· Abstract class cannot be instantiated, but pointers and references of abstract class type can be created