Understanding Abstract Classes and Pure Virtual Functions in C++

Abstract Class

An abstract class serves as a foundation in C++ programming. It is designed to be a base class and must include at least one pure virtual function. The key characteristics are:

  • Base Class: An abstract class is always intended to be a base class in an inheritance hierarchy.
  • Pure Virtual Function: It must contain at least one pure virtual function, providing a blueprint for derived classes.

What is a Pure Virtual Function?

A pure virtual function is a unique feature in C++. It is a function without a body and is declared in the base class. Here's what you need to know:

  • Declaration: It is declared with the syntax virtual void virtualFunName() = 0;.
  • No Definition: The function is not defined in the base class; it's left to be implemented by the derived classes.
  • Override Requirement: A derived class must override the pure virtual function; otherwise, the compiler will raise an error.

Example

Let's take a practical example to illustrate abstract classes and pure virtual functions.

#include<iostream>
using namespace std;

class AbstractInterface {
public:
    virtual void numbers() = 0;  // Pure virtual function
    void input();
    int a, b;
};

void AbstractInterface::input() {
    cout << "Enter the numbers\n";
    cin >> a >> b;
}

class Add : public AbstractInterface {
public:
    void numbers() override {
        int sum = a + b;
        cout << "Sum is " << sum << "\n";
    }
};

class Subtract : public AbstractInterface {
public:
    void numbers() override {
        int diff = a - b;
        cout << "Difference is " << diff << "\n";
    }
};

int main() {
    Add obj1;
    obj1.input();
    obj1.numbers();

    Subtract obj2;
    obj2.input();
    obj2.numbers();

    return 0;
}

Output:

Enter the numbers
5
6
Sum is 11

Enter the numbers
5
6
Difference is -1

In this example, AbstractInterface is an abstract class with a pure virtual function numbers(). The Add and Subtract classes inherit from it, providing their own implementations for the pure virtual function.

Next Post Previous Post
No Comment
Add Comment
comment url