We have a C++ class MyFoo
class MyFoo
{
int a, b = 0;
MyFoo(const ©Obj)
{
this -> a = copyObj.a;
this -> b = copyObj.b;
}
MyFoo()
{
}
MyFoo(int a, int b)
{
this -> a = a;
this -> b = b;
}
// this behaves like copy constructor
MyFoo add(MyFoo copyObj)
{
MyFoo temp;
temp.a = copyObj.a;
temp.b = copyObj.b;
return temp;
}
};
int main()
{
// Why does this syntax even work?
MyFoo myfoo[] = { Myfoo(myfoo[1]), Myfoo(1,2), Myfoo() };
// Using object returned by add()
MyFoo obj1;
MyFoo obj2(10, 20);
// Use obj3 now obj3...
MyFoo obj3 = obj1.add(obj2);
return 0;
}
I have two confusions
Is there any other way to use the temp object in the main() function, returned by add() in the MyFoo class? Do I really have to declare obj3? Isn't some variable hidden etx returned by function?
Why does the array syntax work?
myFoo(myfoo[1])will call copy constructor and put garbage value inside the object because at 1st index we don't have an object yet.