1

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.

1
  • Initialization always invokes constructor and never assignment operator, presence of = is misleading. Commented Nov 5, 2020 at 8:54

1 Answer 1

3

When initializing an object at definition, it's not using assignment even when the = syntax is used.

When you do:

Hero zak = foo; 

it's equivalent to:

Hero zak(foo); 

Which is copy-initialization and as such invokes the copy-constructor.


The problem with

Hero bar = "HelloWorld"; 

is that it's equivalent to:

Hero bar = Hero("HelloWorld"); 

which in turn is equivalent to:

Hero bar(Hero("HelloWorld")); 

And since you don't have a constructor for Hero("HelloWorld") it's invalid.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.