-2

I have the following code:

#include <iostream>


class TestClass {

private:
    int var1, var2;

public:
    TestClass()
        :var1(0), var2(0)
    {}

    TestClass(int x)

    {
        std::cout << "\nOne argument constructor\n";    
    }

    void showData()
    {
        std::cout << "var1 = " << var1 << std::endl;
        std::cout << "var2 = " << var2 << std::endl;
    }

};

int main()
{
    TestClass obj;
    obj.showData();

    obj = 3;
    obj.showData();


    return 0;
}

OUTPUT:

output


My questions:

1 - Why am i able to call a one argument constructor in a statement where the object isn't declared? 2 - Why has the value of var1 and var2 changed after calling one argument constructor?


I ran the code on VS community edition.

Tayyab Mazhar
  • 1,560
  • 10
  • 26

2 Answers2

2

A one-argument constructor that is not marked explicit can be used for an implicit conversion sequence.

In the code obj = 3;, it could be satisfied by implicit conversion of int to TestClass. Your one-argument constructor can be used for this purpose; the code behaves the same as obj = TestClass(3);.

Your program causes undefined behaviour by attempting to display uninitialized variables. The one-argument constructor should initialize var1 and var2.

M.M
  • 138,810
  • 21
  • 208
  • 365
2

In many cases including yours, the compiler is able to automatically generate (among others) an assignment operator of the form TestClass& operator=(const TestClass&). Since TestClass is implicitly constructible from a single integer, obj = 3 is resolved as obj = TestClass(3).

This also explains why var1 and var2 change: the compiler constructs a TestClass object that leaves them uninitialized, then these uninitialized values are copied to your object. If you assign a specific value to var1 and var2 (such as 1), you'll get that value after the copy assignment.

zneak
  • 134,922
  • 42
  • 253
  • 328