Operator overloading c++

https://pastebin.com/0F4xA4Bn
class String{
string s;
public:
void getS(){cout<<s;}
void setS(){cin>>s;}
String operator=(String a){
String b;
b.s=a.s;
return b;
}
};
int main(){
String a;a.setS();
String b;b=a;
b.getS();//no output
}
why no output?

Dont use
String b;
b=a;

Use
String b=a; //Proper format of calling operator overloading

Updated Code:
class String{
string s;
public:
void getS(){cout<<s;}
void setS(){cin>>s;}
String operator=(String a){
String b;
b.s=a.s;
return b;
}
};
int main(){
String a;a.setS();
String b=a;
b.getS();
}

Hit like if u get it.

1 Like

what if i want to do something like:
String b=a;
b=c;
how will this work? or in other words, what if i want to use b=a only?

you want to copy a to b and then b to c ?

copy a to b, then copy c to b.

the string standard lib class allows something like this:
string b=a;
b=c;//a and c are some other string

how can i implement this in my own String class?

you can use this :slight_smile:

class String{
string s;
public:
void getS(){cout<<s;}
void setS(){cin>>s;}
void operator=(const String a) //See this
{
s=a.s;

}
};
int main(){
String a,b;
a.setS();
b=a;
b.getS();//no output
}
you can refer this :slight_smile:
https://www.tutorialspoint.com/cplusplus/assignment_operators_overloading.htm

Hit like if u get it

can you tell why my original code not working?

Cozz operator overloading code is much similar to copy constructor in classes.
You can check the code of copy constructor in C++.

1 Like

I didn’t get it, why is your code working?

whats wrong in my code:
String operator=(String a)
{
String b;
b.s=a.s;
return b;
}