Data conversion from standard type to user-defined type is possible through conversion operator and he classís constructor. But some conversion may take place which we donít want. To prevent conversion operator from performing unwanted conversion, we avoid declaring it. But we may need constructor for building the object. Through the explicit keyword we can prevent unwanted conversions that may be done using the constructor.

class complex
    float real,imag;
  public: complex()
  explicit complex(float r, float i = 0.0)
    real = r;
    imag = i;
  complex operator+(complex c)
    complex t;
    return t;
  void display()
    cout << endl << "real " 
          << real << ", imag " << imag;
int main (int argc, char *argv[])
  complex c1(1.5,3.5);
  c2 = c1 + 1.25;

In the statement: c2=c1+1.25
The compiler would find that here the overloaded operator +() function should get called. When it finds that there is a wrong type on the right hand side of + it would look for a conversion function which can convert float to complex. The two argument constructor can meet this requirement. Hence the compiler would call it. This is an implicit conversion and can be prevented by declaring the constructor as explicit.

About our authors: Team EQA

You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.