Pure Virtual function-Abstract class

Let us try to understand pure virtual function with the help of an example.

#include <iostream>
using namespace std;
class shape {
public:
    virtual void calculateArea() {}
};

class rectangle: public shape {
public:
    void calculateArea() {
        cout << “Rectangle Area calculation” << endl;
    }
};
  • In the above example, calculateArea function is overridden in rectangle class. In shape class, definition is empty since shape class does not know what to calculate.
  • Can we say that empty definition of calculateArea function in shape class is not required. Instead, anyone who inherit shape class must redefine or override calculateArea function in derived class to indicate that calculateArea function must be redefined otherwise compiler error will come.
  • For this purpose, we use pure virtual function.
    class shape {
    public:
        virtual void calculateArea ()=0; //pure virtual function
    };
  • Virtual function becomes pure virtual function by appending “=0” to the virtual function declaration.

  • class with atleast one pure virtual function is called abstract class.

  • Object of an abstract class is not possible.

  • Now, any class who inherit the shape class must override this function. In case user forgets to override pure virtual function in derived class, then compiler error will come if anyone tries to create an object of derived class. In other words, that class also becomes an abstract class.

  • We can define the pure virtual function but class still remains an abstract class i.e. we cannot create a object of that class and class that inherits abstract class still needs to override it.
    void shape::calculateArea() {
        cout << “Shape calculateArea”<< endl;
    }
  • As mentioned in the destructor blog, that destructor can be virtual.Destructor can be pure virtual as well.
    class shape {
    public:
        virtual ~shape()=0;
        virtual void calculateArea() {}
    };

    shape::~shape() {
        cout << “shape destructor” << endl;
    }
  • In the above example, shape class still an abstract class because it has one pure virtual function i.e. destructor.

  • Definition of pure virtual destructor is must. The reason is when object is destructed i.e., object goes out of scope or deleted by delete operator, then destructor is called in reverse order i.e. from derived to base class.When compiler see there is no definition of base class destructor, it throws an error.


Related posts