c++classinitializationconstructmove-assignment-operator

class to class type conversion through constructor method output is 5500 why not 5555


Output is 5500, but why not 5555?

class product {
public:
    int b;
};

class item {
public:
    int a;
    item(product& obj)
    {
        cout << a;
    }
    item() {}
    void display()
    {
        cout << a;
    }
};

int main()
{
    item obj1;
    product obj2;
    obj1.a = 5;
    cout << obj1.a;
    obj1.display();
    obj1 = obj2;
    //object of product class sent into Constructor of item class*
    cout << obj1.a;
    return 0;
}

Here constructor is called of item class and product object is pass through it.


Solution

  • The program has undefined behavior because the used data member a is not initialized.

    This conversion constructor

            item(product &obj)
            {
               cout<<a;
            }
    

    that is used in this assignment statement

    obj1=obj2;
    

    to convert the object obj2 of the type product to an object of the type item does not initialize the data member a. So the data member has an indeterminate value. And this indeterminate value assigned to the data member a of the object obj1 is outputted in the constructor and in this statement

    cout<<obj1.a;
    

    It occurred such a way that the memory occupied by the data member a of the temporary object of the type item contained zeroes. But in general this is not necessary.