In C++ class is made abstract by declaring at least one of its functions as <>strong>pure virtual function. A pure virtual function is specified by placing “= 0” in its declaration. Its implementation must be provided by derived classes.
Let’s see an example of abstract class in C++ which has one abstract method draw(). Its implementation is provided by derived classes: Rectangle and Circle. Both classes have different implementations.
Example
#include <iostream>
using namespace std;
class Shape
{
public:
virtual void draw()=0;
};
class Rectangle: Shape
{
public:
void draw()
{
cout < <“drawing rectangle…” < <endl;
}
};
class Circle : Shape
{
public:
void draw()
{
cout <<“drawing circle…” < <endl;
}
};
int main( ) {
Rectangle rec;
Circle cir;
rec.draw();
cir.draw();
return 0;
}
Output:
drawing rectangle... drawing circle...
Restrictions on abstract classes
Abstract classes can’t be used for:
- Variables or member data
- Argument types
- Function return types
- Types of explicit conversions
If the constructor for an abstract class calls a pure virtual function, either directly or indirectly, the result is undefined. However, constructors and destructors for abstract classes can call other member functions.