C++ Operator Overloading as Member Functions

In C++, you can overload operators as member functions of a class. This allows you to define custom behavior for operators when they are used with objects of your class.

To overload an operator as a member function, you define a function with the name of the operator and the keyword operator followed by the operator symbol. The function should take no arguments (for unary operators) or one argument (for binary operators), and it should return the result of the operation.

Here is an example of overloading the addition operator (+) as a member function:

refer to‮:‬theitroad.com
class MyVector {
public:
    MyVector(int x = 0, int y = 0) : m_x(x), m_y(y) {}
    
    MyVector operator+(const MyVector& other) {
        return MyVector(m_x + other.m_x, m_y + other.m_y);
    }
    
private:
    int m_x, m_y;
};

In this example, we define a class MyVector that represents a two-dimensional vector. We overload the addition operator as a member function, which takes one argument of type MyVector (the right-hand side of the addition) and returns a new MyVector object that represents the sum of the two vectors.

With the addition operator overloaded as a member function, we can now add two MyVector objects using the + operator:

MyVector a(1, 2);
MyVector b(3, 4);
MyVector c = a + b; // Equivalent to c = a.operator+(b);

In this example, we create two MyVector objects a and b, and we add them together using the + operator. The result of the addition is assigned to a third MyVector object c.

Note that when you overload operators as member functions, the left-hand side of the operator is always an object of the class, and the right-hand side is passed as an argument. Therefore, if you want to overload a binary operator with a built-in type on the left-hand side, you need to define a non-member function that takes the built-in type as its first argument, and the object of your class as its second argument.

In general, overloading operators as member functions can make your code more readable and natural, as it allows you to use operators with objects in a way that resembles the usual mathematical notation. However, it can also be less flexible than overloading operators as non-member functions, as you need to modify the class definition to add new operator overloads.