class phone {
public:
phone(int x) { num = x; }
int number(void) { return num; }
void number(int x) { num = x; }
private:
in
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
s to the custom object type. In your case, the code
p1 = 20;
is interpreted as
p1.operator= (20);
Which is, in turn, 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 mark the constructor explicit
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 won't be considered when doing implicit conversions, and the above code will cause an error.