This is legal because C ++ interprets any constructor that can be called with a single argument of type T as a means of implicitly converting from T to the type of a custom object. In your case, the code
p1 = 20;
interpreted as
p1.operator= (20);
Which, in turn, is interpreted as
p1.operator= (phone(20));
This behavior is really weird, and it's almost certainly not what you wanted. To disable it, you can flag the explicit constructor to disable the implicit conversion:
class phone { public: explicit phone(int x) { num = x; } int number(void) { return num; } void number(int x) { num = x; } private: int num; };
Now the constructor will not be taken into account when performing implicit conversions, and the above code will cause an error.
templatetypedef
source share