In previous chapter we saw what is a virtual function. In this chapter we shall see what is a pure virtual function and what is an abstract class.
Pure virtual Functions:
Pure virtual functions are the functions with “=0” at the end of their declarations.
Below is the declaration of pure virtual function:
virtual void display() = 0;
From the above declaration we can say that a pure virtual functions are those without any function definition.
If a class has one pure virtual function, then that class will become an abstract class.
Below are some of the rules of a Pure Virtual Function or Abstract class:
1. A class having a pure virtual function, cannot be used for any operation.
2. The class having a pure virtual function cannot be used to declare any objects.
3. A class inheriting an abstract class needs to implement all the pure virtual functions. If not, the derived class will also become a abstract class.
Example for a pure virtual function:
#include<iostream>
//for more interview questions visit www.MyPlacementPrep.com
using namespace std;
class Base
{
public:
virtual void display() = 0;
};
class Derived: public Base
{
public:
void display()
{
cout<<"In display class"<<endl;
}
};
int main()
{
Base *bPtr;
Derived dObj;
bPtr = &dObj;
bPtr-> display();
return 0;
}
Output:
In display class
In the above program, “Base” class is having a pure virtual function. The derived class “Derived” implemented all the pure virtual functions got from the base class.
Then we created an object of derived class and assigned it to base class pointer. And finally called the display().
Why do we need Abstract Class?
Consider a situation, that you need a skeleton where in all the derived classes need to implement those function. To madidate them to implement those functions, we need a Abstract class.
For example:
We have an “Animal” class and we need all the derived classes needs to implement “makeSound” function. We can achieve it as below:
#include<iostream>
//for more interview questions visit www.MyPlacementPrep.com
using namespace std;
class Animal
{
public:
virtual void makeSound() = 0;
void display()
{
cout<<"In animal function"<<endl;
}
};
class Dog: public Animal
{
public:
void makeSound()
{
cout<<"Bow Bow"<<endl;
}
};
class Cat: public Animal
{
public:
void makeSound()
{
cout<<"Meow Meow"<<endl;
}
};
int main()
{
Dog dog;
dog.makeSound();
Cat cat;
cat.makeSound();
return 0;
}
Output:
Bow Bow
Meow Meow
Note:
It is possible to have pointers and references of abstract class type.
#include<iostream>
//for more interview questions visit www.MyPlacementPrep.com
using namespace std;
class Base
{
public:
virtual void display() = 0;
};
class Derived: public Base
{
public:
void display()
{
cout<<"In display class"<<endl;
}
};
int main()
{
Base *bPtr = new Derived();
bPtr-> display();
return 0;
}
Output:
In display class