Software & Finance





C++ - Abstract Class





A class with at least one pure virtual function is called abstract class. We can not instantiate an abstract class.

A pure virtual function is nothing but no implementation and assigned with 0. For example:
virtual void draw() = 0; You can not instantiate the Shape class in the given example. In order to instantiate, you must override this function with a derived class. In the sample code given below, Circle is a dervied class dervied from the class Shape.

Source Code


 

class Shape

{

    protected:

    virtual void draw() = 0; // pure virtual function

}

 

class Circle : public Shape

{

    int r;

public:

 

    Circle()

    {

        std::cout << "Circle\n\n";

    }

 

    virtual void draw() {}

    virtual void display() { }

};

void main()

{

    Shape s; // error C2259: 'Shape' : cannot instantiate abstract class due to following members: 'void Shape::draw(void)' : is abstract

}