C++ Programming Tips: Writing Non-Member Functions for Type Conversion of ‘this’

Let’s start with an example. Suppose we create a class to represent money. Although it was previously mentioned to avoid implicit conversions as much as possible, in this case, it is quite reasonable to implicitly convert an int to money:

class Money{public:    // Default constructor - supports implicit conversion    Money(int num) : num(num){};

If we want to implement multiplication for Money, the first thought is to overload the * operator within the class:

class Money{public:    // Default constructor - supports implicit conversion    Money(int num) : num(num){}    // Overload * operator    const Money operator*(const Money& money) const{ ... }}

This seems correct, but it leads to a serious problem:

Money B(10);Money A = B*20; // Correct executionMoney C = 20*B; // Error

The commutative property of multiplication does not hold! It is clear that the failure occurs because 20*B calls the int’s operator*, which fails.At this point, as we mentioned, since ‘this’ (referring to int*) also requires type conversion, we need to use a non-member function:

const Money operator*(const Money& money1,const Money& money2) { ... }

Now the commutative property of multiplication works correctly.

Leave a Comment