#include<iostream>
usingnamespace std;
class A
{
// data members of A
public:
A() { cout << "\n A's constructor"; /* Initialize data members */ }
A(const A &a) { cout << "\n A's Copy constructor"; /* Copy data members */ }
A& operator= (const A &a) // Assignemt Operator
{
// Handle self-assignment:
if(this == &a) return *this;
// Copy data members
cout << "\n A's Assignment Operator"; return *this;
}
};
class B
{
A a;
// Other members of B
public:
B(A &a):a(a) { cout << "\n B's constructor"; }
};
int main()
{
A a;
B b(a);
return 0;
}
The o/p is :
A's constructor
A's Copy constructor
B's constructor
In class B, A a; should call A::A() and then in initializer list at : B(A &a):a(a) , it should call Assignment operator.
That's not how it works. When you list an object in the constructor's initialization list it means you are deciding which constructor should be used to construct the object. In your code you say a should be constructed using the copy constructor so that is what happens.
If the constructor was B(A &a):a(){ this->a = a; } or B(A &a){ this->a = a; } then it would work as you said. First a is constructed using the default constructor and then the copy assignment operator is called.
When creating an object of type Foo (we assume that memory has already been allocated for the entire Foo object), three operations will be done in order:
1. The base class (subobject) of Foo is constructed.
2. The member variables are constructed in the order they occur in the definition of Foo.
3. The body of the constructor of Foo is executed.
In other words:
The construction of subobject B::a does start after the construction of B object has started and completes before the body of B::B(A&) is executed.
The initializer list syntax allows us to pass a parameter to the construction of B::a, and the parameter that you do use makes the construction of B::a to use the copy constructor of A to construct the B::a.
If you want to call that action "defining the a", then you define the a with copy constructor of A. The a is created at that point in execution, not before.