Home > Back-end >  Overloading different types in C
Overloading different types in C

Time:05-18

Suppose we have the following class:

class Rational { // Represents rational number. n=1/2=d for example.
public:
  int n = 0;
  int d = 1;
};

Rational x = Rational();
x.n = 1;
x.d = 2;

Is it possible to do overloading such that 3 * x would give 3/2 instead of an error?

My teacher said that overloading happens only between objects of the same type, but why can we do overloading between cout which is of type ostream and an object of type Rational and not of the type int and Rational?

CodePudding user response:

You may write for example

Rational operator *( const Rational &r, int x )
{
    return { r.n * x, r.d };
}

Rational operator *( int x, const Rational &r )
{
    return { r.n * x, r.d };
}

You may overload operators for user defined types. For a binary operator at least one of operands must be of a user defined type.

From the C 20 Standard (12.4.2.3 Operators in expressions)

2 If either operand has a type that is a class or an enumeration, a user-defined operator function can be declared that implements this operator or a user-defined conversion can be necessary to convert the operand to a type that is appropriate for a built-in operator. In this case, overload resolution is used to determine which operator function or built-in operator is to be invoked to implement the operator. Therefore, the operator notation is first transformed to the equivalent function-call notation as summarized in Table 15 (where @ denotes one of the operators covered in the specified subclause). However, the operands are sequenced in the order prescribed for the built-in operator (7.6).

  • Related