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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With