Abstract Class and Pure Virtual Function in C++ Programming

In C++ programming, sometimes inheritance is used only for the better visualization of data and you do not need to create any object of base class. For example: If you want to calculate area of different objects like: circle and square then, you can inherit these classes from a shape because it helps to visualize the problem but, you do not need to create any object of shape. In such case, you can declare shape as a abstract class. If you try to create object of a abstract class, compiler shows error.

Declaration of a Abstract Class
If expression =0 is added to a virtual function then, that function is becomes pure virtual function. Note that, adding =0 to virtual function does not assign value, it simply indicates the virtual function is a pure function. If a base class contains at least one virtual function then, that class is known as abstract class.

Example to Demonstrate the Use of Abstract class
#include <iostream>
using namespace std;
class Shape /* Abstract class */
{
    protected:
        float l;
    public:
        void get_data( ) /* Note: this function is not virtual. */
        {
        cin>>l;
        }
        virtual float area( ) = 0; /* Pure virtual function */
};

class Square : public Shape
{
    public:
        float area( )
        { return l*l; }
};

class Circle : public Shape
{
    public:
        float area( )
        { return 3.14*l*l; }
};

int main( )
{
    Square s;
    Circle c;
    cout<<"Enter length to calculate area of a square: ";
    s.get_data();
    cout<<"Area of square: "<<s.area();
    cout<<"\nEnter radius to calcuate area of a circle:";
    c.get_data();
    cout<<"Area of circle: "<<c.area();
    return 0;
}

In this program, pure virtual function virtual float area( ) = 0; is defined inside class Shape, so this class is an abstract class and you cannot create object of class Shape.

No comments:

Post a Comment