Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why constructor is being called twice

Tags:

c++

I do not understand how constructors work?

Here I have declared an object obj2. It calls constructor abc(), which is perfectly fine.

But when I am assigning

obj2 =  100 

Why does compiler allow initializing an integer to a class object? If at all it is allowing then how it is destroying the object and then how it is calling another parameterized constructor.

Now I have another question why destructor is called only once as there are two objects?

One more doubt I have is, compiler is not doing anything with default constructor then why default constructor is required?

class abc{
public:
    int a, b;

    abc()
    {a = 0; b = 0;}

    abc(int x)
    {a = x;}

    ~abc()
    {std::cout << "Destructor Called\n";}
};
int main()
{
    abc obj1;
    cout << "OBJ1 " << obj1.a << "..." << obj1.b << "\n";
    abc obj2;
    cout << "OBJ2 " << obj2.a << "..." << obj2.b << "\n";
    obj2 = 100;
    cout << "OBJ2 " << obj2.a << "\n";
system("pause");
return 0;
}

output:

OBJ1 0...0
OBJ2 0...0
Destructor Called
OBJ2 100
like image 740
Rasmi Ranjan Nayak Avatar asked Sep 27 '13 18:09

Rasmi Ranjan Nayak


1 Answers

But when I am assigning obj2 = 100, how the compiler is allowing initializing an integer to a class object?

This is because when you do the following:

obj2 = 100;

this one will first call abc(int x) to generate an object of the class, then call the default copy assignment operator (since no user-defined is provided) to assign the value 100 to existing obj2. After the assignment, the temporary object is destructed.

If you do not desire this effect, mark the constructor as explict to avoid implicit calls.

explicit abc(int x) {
    //do something
}
like image 98
taocp Avatar answered Oct 19 '22 23:10

taocp