Open In App

How to Overload the Multiplication Operator in C++?

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the multiplication operator is a binary operator that is used to find the product of two numeric values. In this article, we are going to learn how to overload the multiplication operator for a class in C++.

Overloading Multiplication Operator in C++

C++ provides the functionality of operator overloading which allows the user to modify the working or to define its working for a new class. To overload an operator for a class, we need to define a special function with the operator symbol as the public member function of the class.

C++ Program to Overload the Multiplication Operator

Consider a class ‘vector’ that represents the coordinate of a point in the three-dimensional plane. Now let’s overload the multiplication operator so that it can perform the cross product of two vectors.

C++




// C++ Program to implement overload * operator without
// using friend function
  
#include <iostream>
using namespace std;
  
class Vector {
    int x, y, z;
  
public:
    Vector(int x, int y, int z)
    {
        this->x = x;
        this->y = y;
        this->z = z;
    }
  
    void getVector()
    {
        cout << x << "i" << showpos << y << "j" << z
             << "k\n"
             << noshowpos;
    }
  
    // Overloading * operator to perform cross product of
    // two vectors, the left operand is *this object
    Vector operator*(Vector const& v)
    {
        int x = (this->y * v.z) - (this->z * v.y);
        int y = (this->z * v.x) - (this->x * v.z);
        int z = (this->x * v.y) - (this->y * v.x);
        return Vector(x, y, z);
    }
};
  
// driver code
int main()
{
    Vector v1(2, -3, 7), v2(4, 2, -2);
    cout << "Vector 1: ";
    v1.getVector();
    cout << "Vector 2: ";
    v2.getVector();
  
    // multiplying two vector
    Vector v3 = v1 * v2; // Calling Operator function
    cout << "Vector 3: ";
    v3.getVector();
}


Output

Vector 1: 2i-3j+7k
Vector 2: 4i+2j-2k
Vector 3: -8i+32j+16k

Explanation

Here Vector v1 is calling the operator * function with Vector v2 as argument. The result is stored in Vector v3. If we wouldn’t have defined the multiplication operator for our data type, the statement v1 * v2 might have lead to an error.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads