Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 718
JavaMan Avatar asked Sep 21 '26 09:09

JavaMan


1 Answers

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"

like image 134
JavaMan Avatar answered Sep 24 '26 00:09

JavaMan