Search code examples
c++oopconstructordelete-operatorobject-initialization

Object initialization syntax in C++


I noticed a few strange errors when I was trying to initialize constructors. It's easiest if I just show them.

#include <iostream>


class MyClass {

public:

    int var1, var2, var3;

    MyClass() {

        var1, var2, var3 = 0;

    }

    MyClass(int one, int two, int three) {

        var1 = one;
        var2 = two;
        var3 = three;
    }

};


int main()
{
    MyClass object1(5, 6, 7);
    std::cout << object1.var1; // This works

    MyClass object2();
    std::cout << object2.var1; //Error object must have class type.

    MyClass object3 = MyClass();
    std::cout << object3.var1; //Now it works for some reason

    delete &object1;
    MyClass ojbect1(5, 6, 7); //error redefinition; multiple initialization
}

As you can see, for some reason, when I initialize object2, the values won't print unless, as with object3, the syntax is written as MyClass object3 = MyClass();

Furthermore when I delete object1 I have to use a & operator. This surprised me considering in this question Deleting an object in C++ they don't use the ampersand.

Finally, when I try to re-initialize myobject, the compiler complains that there are multiple definitions. I tried leaving out the MyClass keyword and it still wouldn't allow it.

Now I can certainly make the program do what I want with various workarounds, but I don't understand why these things can't be done the way I wrote them here.


Solution

  • MyClass object2();
    std::cout << object2.var1; 
    

    doesn't work since object2 is parsed as "a function that takes no arguments and returns a MyClass". See Most vexing parse: why doesn't A a(()); work?

    delete &object1; 
    

    is cause for undefined behavior. You can delete only objects that were created using new.

    MyClass object1(5, 6, 7);
    

    is a problem like the compiler told. You cannot redeclare the name in the same scope. If you want it have a new value, you can use:

    object1 = MyClass(5, 6, 7);