I have the following code and i don’t understand, why at the creation of object b, the constructor of class A doesn’t called…….I will appreciate a little help.hank you very much.
#include <iostream>
using namespace std;
class MyClass
{
int x;
public:
MyClass(int y);
MyClass(MyClass &my)
{
x = my.x;
cout << "My class created by copy" << endl;
}
};
MyClass::MyClass(int y)
{
x = y;
cout << "My class created" << endl;
}
class A {
MyClass k;
public:
A(MyClass &my) : k(my) {
cout << "A created" << endl;
}
};
class B {
A data;
public:
B(A& aa) : data(aa)
{
cout << "B created" << endl;
}
};
int main()
{
MyClass obj(100);
A a(obj);
B b(a);
return 0;
}
execution:
My class created
My class created by copy
A created
My Class created by copy
B created
A‘s copy constructor is called, not the constructor you have defined. Since you have neither defined it nor deleted it, the default constructor is called. The default constructor will call the copy constructor of each of the member variables; I believe it is in the order of declaration.