-
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?
Code:
Class MyClass{
public:
MyClass(int);//constructor
...
//+ operator overloaded
MyClass operator+(const MyClass &objetc)const
{
//how this can work and why?
return MyClass(localData + object.localData)
}
...
};
int main()
{
MyClass n1;
MyClass n2(20);
Mclass n3(6);
n1 = n2+n3;
return 0;
}
thanks for any help
-
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:
Code:
char myString[] = "hello world";
char ch;
for(int i = 0; i < strlen(myString); ++i)
{
if(isalpha(ch))
cout << "element " << i << " of myString is a letter" << endl;
else
cout << "element " << i << " of myString isn't a letter" << endl;
}
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.
-