I have a situation where the constructor is not being called:
#include <iostream> using namespace std; int main () { class yoyo { public: int i; yoyo() { i = 0; cout << "defaultly initialized to 0" << endl; } yoyo (int j) : i(j) { cout << "initialized to " << j << endl; } }; int i; yoyo a; cout << "Hello1, i: " << ai << endl; yoyo b(5); cout << "Hello2, i: " << bi << endl; yoyo c = b; /* 1 */ cout << "Hello3, i: " << ci << endl; return 0; }
Output:
defaultly initialized to 0 Hello1, i: 0 initialized to 5 Hello2, i: 5 Hello3, i: 5
(Note: there was nothing between Hello2 and Hello3)
If I changed the program as follows:
#include <iostream> using namespace std; int main () { class yoyo { public: int i; yoyo() { i = 0; cout << "defaultly initialized to 0" << endl; } yoyo (int j) : i(j) { cout << "initialized to " << j << endl; } }; int i; yoyo a; cout << "Hello1, i: " << ai << endl; yoyo b(5); cout << "Hello2, i: " << bi << endl; yoyo c; c = b; /* 1 */ cout << "Hello3, i: " << ci << endl; return 0; }
(The only difference is in the line marked with the symbol / * 1 * /)
Now the conclusion:
defaultly initialized to 0 Hello1, i: 0 initialized to 5 Hello2, i: 5 defaultly initialized to 0 Hello3, i: 5
Now between Hello2 and Hello3 there is a constructor call. My question is why in the first case there is no (visible) constructor call?
source share