I’m playing with operator overloading in C++, specifically the assignment operator “=”.
So, at a time, I’m able to do this:
MyClass var1;
var1 = "string";
But, it gives me an error when I try to do this:
MyClass var2 = "string";
Somebody knows why? And how can I make it possible?
The second example isn’t calling
operator=, it’s calling a conversion constructor forconst char [], or whatever you’d be using it for internally, as long as it can convert from that (e.g.std::string), which doesn’t exist as of yet. You can see one implemented in std”OrgnlDave’s answer. It’s almost identical toThe latter, though, is explicit, whereas the former is implicit. To see the difference, make a constructor and mark it
explicit. The code here will work, but yours won’t. This can save confusion when you, for example, pass a string by accident instead of aMyClass, and it gets implicitly converted when it isn’t even meant to be aMyClassin the first place.