I got some similar question in my internship MCQ test.
CODE
#include <iostream>
#define DEFAULT_VALUE -1
using namespace std;
class Base
{
public:
int variable;
Base(void) : variable(DEFAULT_VALUE)
{
cout << "Base Class Default Constructor Called.\n";
}
Base(int increment_value)
{
Base();
variable += increment_value;
cout << "Base Class Parametrized Constructor Called.\n";
}
~Base(void)
{
cout << "Base Class Destructor Called.\n";
}
};
int main(void)
{
Base obj(5);
cout << "Value of the variable of base class is: " << obj.variable << '\n';
return 0;
}
OUTPUT
Base Class Default Constructor Called.
Base Class Destructor Called.
Base Class Parametrized Constructor Called.
Value of the variable of base class is: 5
Base Class Destructor Called.
Here It the final value of variable
should be 4. But it's 5!
But when the code is written like this.
CODE
#include <iostream>
#define DEFAULT_VALUE -1
using namespace std;
class Base
{
public:
int variable;
Base(void) : variable(DEFAULT_VALUE)
{
cout << "Base Class Default Constructor Called.\n";
}
Base(int increment_value) : Base()
{
variable += increment_value;
cout << "Base Class Parametrized Constructor Called.\n";
}
~Base(void)
{
cout << "Base Class Destructor Called.\n";
}
};
int main(void)
{
Base obj(5);
cout << "Value of the variable of base class is: " << obj.variable << '\n';
return 0;
}
OUTPUT
Base Class Default Constructor Called.
Base Class Parametrized Constructor Called.
Value of the variable of base class is: 4
Base Class Destructor Called.
Now the value of the variable
is 4 (and it should be).
Looks like in the previous case it is creating another instance of the same class and calling it's default constructor. But why that didn't happened in this case, when the default constructor is called in the initialization list.
And what's the reason of creating another instance when calling the default constructor in the parametrized constructor?