top of page

Abstract class

 

A class which can not be instantiated is said to be an abstract class. An abstract class works as an interface which derived classes should implement.

 

In C++, abstract class is implemented with the help of pure virtual functions.

 

Pure Virtual Function

 

A function is said to be a pure virtual function, if it has no definition but has only declaration.

 

class abc

{

  public:

     virtual int foo()=0;

};


Here the function foo() is virtual and also is set to 0. And it has no definition. So foo() is a pure virtual function.

 

When a class has at least one pure virtual function, it is incomplete and so no objects can be created from that class.

 

Such a class becomes an abstract class.

Abstract classes are used to enforce some interfaces on derived classes.

For example, if you have shape class, and you want all derived classes of shape class to define draw() function, then you should make draw() as pure virtual function. Now all inherited classes of shape should define draw() function.

 

As we have seen above, to make a function as pure virtual function, you should use =0 at the end of virtual function declaration and you should not define that function.

Here findArea() function is pure virtual function. As class Polygon has pure virtual function, it is an abstract class. Which means no objects can be created from Polygon class.  And the code  produces compiler error.
 

Any derived class of abstract class MUST define pure virtual function. If it does not, derived class also becomes abstract class.

 

Let us derive two classes from our previous abstract class A.

Here Polygon obj1; is obviously wrong as Polygon is an abstract class (it has pure virtual function findArea()). Square obj3 also produces error because Square is also an abstract class, because it has not defined the inherited pure virtual function findArea().

 


Also note that, in the code above, Polygon obj1 produces error, but Polygon *ptr does not produce error.

 

Because by defining ptr as a pointer of class Polygon, we have not yet created any object. And ptr may point to any of the  derived classes of Polygon, which may be non-abstract.  

bottom of page