Search code examples
c++assignment-operator

can an assignment operator be overloaded to assign a string literal to a user definded string type?


This first section is a web example

Assignment:

You can assign a C++ string, a C string, or a C string literal to a C++ string.

Examples:

string s1 = "original string";
string s2 = "new string";
char s3[20] = "another string";

s1 = s2;//s1 changed to "new string"
s1 = s3;//s1 changed to "another string"
s1 = "yet another string";
   //s1 changed to "yet another string"
   //Once again, this works because.
   //operator overloading.

This is technically my question below

class my_string{
public:
.
.
my_string& operator=(const my_string&);
.
.
.
};

if this is the only assignment operator overload allowed then how does s1 get the value of "yet another string" in the above example?


Solution

  • If I understand your question correctly, that's because it is not the only assignment operator, there are other overloaded definitions. These are for C++98, there are others for C++11.

    string& operator= (const string& str);
    string& operator= (const char* s);
    string& operator= (char c);
    

    http://www.cplusplus.com/reference/string/string/operator=/

    s1 = "yet another string"; uses the second operator in the list, while s1 = s2; uses the first.