+ 4

When we have to use operator overloading?

when it is required?

11th Mar 2017, 9:38 AM
Feruza
Feruza - avatar
4 Respostas
+ 6
Now suppose the Sample class has two member variables, int a,b; We have only one way to access member variables of class, i.e. by object. to get variables a and b, we do it as- S1.a and S1.b or S2.a and S2.b , like this. Now if you add S1+S2 it means you are adding their variables a and b. but which two variables will be added? are they- S1.a+S2.a? S1.b+S2.b? S1.a+S2.b? S1.b+S2.a? we can't tell this. So to get this result to be correct, we overload + operator.
11th Mar 2017, 6:12 PM
Sachin Artani
Sachin Artani - avatar
+ 4
When you want to operate two objects, you will need the operator to be overloaded to be capable of perform operation between objects. like adding two objects S1 and S2 of class Sample- S3=S1+S2; to perform such operation, you must overload + operator.
11th Mar 2017, 9:42 AM
Sachin Artani
Sachin Artani - avatar
0
why we don't simply add them,instead of overloading
11th Mar 2017, 11:15 AM
Feruza
Feruza - avatar
0
s3=s1.tostring()+s2.tostring();
13th Mar 2017, 5:11 AM
Mr.Miri