C++ array declare weird syntax assign garbage value

Viewed 90

We have a C++ class MyFoo

class MyFoo
{
    int a, b = 0;

    MyFoo(const &copyObj)
    {
        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

  1. 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?

  2. 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.

0 Answers
Related