Konstantin Vinogradov
Konstantin Vinogradov

Reputation: 29

C++ assignment operator during declaration

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.

Upvotes: 1

Views: 859

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

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.

Upvotes: 3

Related Questions