Last Updated:

Defining and Overloading Class Statements in C++

In C++, you can define custom operators for your own data types. The operator is defined as a normal member function of the class, only after the return type is determined is the keyword . operator

Example of defining an addition operator:

int operator+ (int value) { return number + value; }

The operator can be unary or binary. The unary operator does not accept any arguments. For example, the negation operator is "!". The binary operator takes an additional parameter. For example, in the case of addition, the second term is taken.

To clarify the picture, let's try to write a class that will describe a simple fraction with an integer and denominator. And define the addition, subtraction, multiplication, and division operators for this class.simple_fraction

/*
 * A class describing a simple fraction
*/
class simple_fraction
{
public:
    simple_fraction(int numerator, int denominator)
    {
        if (denominator == 0) // Divide By Zero Error
            throw std::runtime_error("zero division error");
        this->numerator = numerator;
        this->denominator = denominator;
    }

    // Defining basic math operations for a simple fraction
    double operator+ (int val) { return number() + val; } // Addition
    double operator- (int val) { return number() - val; } // Subtraction
    double operator* (int val) { return number() * val; } // Multiplication
    double operator/ (int val) // Division
    {
        if (val == 0) {
            throw std::runtime_error("zero division error");
        }
        return number() / val;
    }

    // Getting the value of the fraction as a regular double number
    double number() { return numerator / (double) denominator; }
private:
    int numerator; // Numerator
    int denominator; // Denominator
};

For the division operation, we also did a zero division check.

Example of using the class :simple_fraction

// Simple fraction 2/3
simple_fraction fr(2, 3);

double sum = fr + 10; // sum
double diff = fr - 10; // difference
double factor = fr * 10; // work
double div = fr / 10; // private

Operators can be overloaded in the same way as regular class member functions. For example, you can overload an addition operator for two prime fractions that will return a new simple fraction. Then, we have to bring the fractions to a common denominator and return another simple fraction.

Task: Improve the class. Overload the addition, subtraction, multiplication, and division operators so that you can perform operations on two prime fractions and produce a new simple fraction. Implement bringing two fractions to a common denominator.simple_fraction

An example of using the future class:

simple_fraction fr1(2, 3);
simple_fraction fr2(3, 4);

// 2/3 + 3/4 is 17/12
simple_fraction sum = fr1 + fr2;