This is my class Hero with two overload assignment operators - Hero to Hero and String to Hero.
#include <iostream> class Hero { private: int x; std::string name; public: Hero():x(42), name("JohnDoe") {}; Hero(int a, std::string b):x(a), name(b) {}; void print(){ std::cout<<name<<" : "<<x<<"\n"; } const Hero &operator =(const Hero &other){ std::cout<<"Overloaded Assignment class to class! \n"; x = other.x; name = other.name; return *this; } const Hero &operator =(const std::string N){ std::cout<<"Overloaded Assignment from string! \n"; x = 777; name = N; return *this; } }; int main(){ Hero foo(42, "Hercules"); Hero zak = foo; // Regular assignmnet, not the overloaded // Hero bar = "HelloWorld"; <<<< Illegal Hero zoo(HelloWorld",42); << Ok, but here we use constructor, not an assignment operator Hero bar; bar = "Ayax"; // "Overloaded Assignment from string! \n"; zak = bar; //"Overloaded Assignment class to class! \n"; zak.print(); bar.print(); } And the produced result:
Overloaded Assignment from string! Overloaded Assignment class to class! Ayax : 777 Ayax : 777 Why can't I use overloaded operators for variable initialization in declaration?
In the line Hero zak = foo; compiler uses non-overloaded operator and the string Hero bar = "HelloWorld" is just illegal.
=is misleading.