Possible Duplicate:
C++ initialization lists
What is the difference between member-wise initialization and direct initialization in a class? What is the difference between the two constructors defined in the class?
class A
{
public:
int x;
int y;
A(int a, int b) : x(a), y(b)
{}
A(int a, int b)
{
x = a;
y = b;
}
};
The theoretical answers have been given by other members.
Pragmatically, member-wise initialization is used in these cases :
MyClass & mMyClass
) in your class. You need to do a member-wise initialization, otherwise, it doesn't compile.const MyClass mMyClass
). You also need to do a member-wise initialization, otherwise, it doesn't compile.MyClass mMyClass
with no constructor MyClass::MyClass()
). You also need to do a member-wise initialization, otherwise, it doesn't compile.MyClass mMyClass
and sizeof(MyClass) = 1000000000
). With member-wise initialization, you build it only once. With direct initialization in the constructor, it is built twice.First one uses initialization and second one does NOT use initialization, it uses assignment. In the second one, the members x
and y
are default-initialized first (with zero), and then they're assigned with a
and b
respectively.
Also note that in the second one, members are default initialized only if the types of members are having non-trivial default constructor. Otherwise, there is no initialization (as @James noted in the comment).
Now see this topic to know:
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