Pure Virtual Function and Abstract Class in C++

Mannan Ul Haq
0

Pure Virtual Function:

A pure virtual function is a function declared in a base class that has no implementation. It is declared using the `virtual` keyword followed by `= 0` at the end of the function declaration. A pure virtual function is a placeholder function that is intended to be overridden in derived classes. It serves as an interface for derived classes to implement their own versions of the function.


Syntax:

class Base
{
public:

	virtual void pureVirtualFunction() = 0;
};


Abstract Class:

An abstract class is a class that contains at least one pure virtual function. It is designed to be a base class from which other classes can be derived. Objects of abstract classes cannot be created, but pointers and references of abstract class types can be used.


Example:


class Shape
{
public:

    virtual void calculateArea() = 0;  // Pure virtual function
};

class Circle : public Shape
{
private:
    double radius;

public:

    Circle(double r)
    {
        radius = r;
    }

    void calculateArea() override
    {
        double area = 3.14 * radius * radius;
        cout << "Area of the Circle: " << area << endl;
    }
};

class Rectangle : public Shape
{
private:
    double length;
    double width;

public:

    Rectangle(double l, double w)
    {
        length = l;
        width = w;
    }

    void calculateArea() override
    {
        double area = length * width;
        cout << "Area of the Rectangle: " << area << endl;
    }
};

int main()
{
    Shape* shapePtr;
    Circle circle(5.0);
    Rectangle rectangle(3.0, 4.0);

    shapePtr = &circle;
    shapePtr->calculateArea();  // Output: Area of the Circle: 78.5

    shapePtr = &rectangle;
    shapePtr->calculateArea();  // Output: Area of the Rectangle: 12.0

    return 0;
}


In this example, the `Shape` class is an abstract class with the pure virtual function `calculateArea()`. The `Circle` and `Rectangle` classes inherit from the `Shape` class and provide their own implementations of the `calculateArea()` function.


Since `Shape` is an abstract class, objects of `Shape` cannot be created. However, we can create pointers of type `Shape*` and use them to point to objects of derived classes. This allows us to call the overridden `calculateArea()` function based on the actual object type.


Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !