4
class Complex
{
private:
double real;
double imag;

public:
// Default constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

// A method to compare to Complex numbers
bool operator == (Complex rhs) {
   return (real == rhs.real && imag == rhs.imag)? true : false;
}
};

int main()
{
// a Complex object
Complex com1(3.0, 0.0);

if (com1 == 3.0)
   cout << "Same";
else
   cout << "Not Same";
 return 0;
}

Output: Same

Why this code gives output as Same, how the conversion constructor in working here, please explain, Many many thanks in advance

Luv
  • 5,381
  • 9
  • 48
  • 61

2 Answers2

11

A conversion constructor is any non-explicit constructor callable with one argument. In your code sample, as the Complex constructor provides default values for its parameters, it can be called with a single argument (say 3.0). And since such constructor is not marked explicit, then it is a valid conversion constructor.

When you do com1 == 3.0 --given that there is no operator == between Complex and double-- a conversion constructor is invoked. So your code is equivalent to this:

if( com1 == Complex(3.0) )
K-ballo
  • 80,396
  • 20
  • 159
  • 169
1

In your example, the compiler sees the == operator being used on a complex object and tries to find a way to make it work. There's only one operator== and it requires a complex argument. Since there's a complex constructor that takes a double and is not marked explicit, it uses that to generate a temporary complex object which it then passes to operator==.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622