returning a constructor?
//hi i saw an example of the + operator overloaded and i see that that operator+ function returns a constructor what is the logic behind this?
thanks for any help
//+ operator overloaded
MyClass operator+(const MyClass &objetc)const
//how this can work and why?
return MyClass(localData + object.localData)
n1 = n2+n3;
It's a form of optimization. In the code you have listed you can return anything that resolves to a MyClass object. Clearly, the MyClass constructor will return a MyClass object which can then act as the return object for + operator. It's sort of like using isalpha() in the following syntax:
here, isalpha() returns a value that can be interpretted as true or false, which is what if() is looking for, so it works just fine.
char myString = "hello world";
for(int i = 0; i < strlen(myString); ++i)
cout << "element " << i << " of myString is a letter" << endl;
cout << "element " << i << " of myString isn't a letter" << endl;