Search code examples
c++visual-studiotype-conversionexplicit-constructor

C++ Constructor for Implicit Type Conversion


I have these codes:

class Type2 {
public:
  Type2(const Type1 & type);
  Type2(int);
const Type2 & operator=(const Type2 & type2);
//....
};

...
  Type1 t1(13);
  Type2 t2(4);

  t2=t1;

As I understood, the 1-argument constructors of Type2 each without an explicit keyword should mean any Type1 objects or int values can be implicitly conveted to Type2 objects.

But in the last line t2=t1;, MS Visual Studio gives me this compile error:

....error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Type1' (or there is no acceptable conversion)....

Seems like MS Visual Studio insisting t2=t1; must match an assignment operator with lhs=Type2 and rhs=Type1. Why can't it implicitly cast rhs to t2 and then do the copying with the Type2=Type2 operator?


Solution

  • I've found the answer. Because my Type1 got a conversion operator

        class Type1 {
        public:
            Type1 (int );
            operator  Type2() ;//casting to Type2
    
        ....
        };
    

    This is something called "dual-direction implicit conversion"