Monday, July 15, 2024

Simple Calculator Using Abstraction in C++

 


Program Listing

#include <iostream>


// Abstract class for calculator operations

class Operation {

public:

    virtual double calculate(double a, double b) = 0;

};


// Concrete subclasses for each operation

class Addition : public Operation {

public:

    double calculate(double a, double b) override {

        return a + b;

    }

};


class Subtraction : public Operation {

public:

    double calculate(double a, double b) override {

        return a - b;

    }

};


class Multiplication : public Operation {

public:

    double calculate(double a, double b) override {

        return a * b;

    }

};


class Division : public Operation {

public:

    double calculate(double a, double b) override {

        if (b == 0) {

            std::cerr << "Error: Division by zero is not allowed." << std::endl;

            return 0; // Return 0 as an error value

        }

        return a / b;

    }

};


int main() {

    double num1, num2;

    char operation;


    std::cout <<"\n\n\tSimple Calculator Using Abstraction in C++\n";

    std::cout << "\n\tGive two numbers: ";

    std::cin >> num1 >> num2;


    std::cout << "\tEnter the operation (+, -, *, /): ";

    std::cin >> operation;


    Operation* op = nullptr;


    switch (operation) {

        case '+':

            op = new Addition();

            break;

        case '-':

            op = new Subtraction();

            break;

        case '*':

            op = new Multiplication();

            break;

        case '/':

            op = new Division();

            break;

        default:

            std::cerr << "\tError: Invalid operation." << std::endl;

            return 1;

    }


    double result = op->calculate(num1, num2);


    std::cout << "\n\tThe Result: " << result << std::endl;

     std::cout << "\n\n\tEnd of Program. Thank you for using this program." << std::endl;

    delete op;


    return 0;

}


No comments:

Post a Comment