Table of Contents
1. Conversion Constructor
#include <iostream>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
// no default arguments -> a conversion constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// A method to compare two 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
Explanation: There are two implicit conversions happened in this code snippet.
Complex com1 = {3.0, 0.0};
Use 2 double numbers to construct a complex object.if (com1 == 3.0)
Use 1 double number to construct a complex object.
2. Explicit Specifier
If we add explicit
before Constructor, we then will get an error.
class Complex
{
private:
double real;
double imag;
public:
// no default arguments -> a conversion constructor
explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// A method to compare two Complex numbers
bool operator == (Complex rhs) {
return (real == rhs.real && imag == rhs.imag)? true : false;
}
};
Output: error: chosen constructor is explicit in copy-initialization
.
3. Explicitly Typecast
int main()
{
// a Complex object
Complex com1(3.0, 0.0);
if (com1 == static_cast<Complex>(3.0))
cout << "Same";
else
cout << "Not Same";
return 0;
}
Output: Same