I ran into the following definition of a function that looked rather unusual to me. Can somebody explain the rules of the definition or/and provide a link where it would be explained.
1 2 3 4 5 6 7 8
class A{
public:
A(int n=0);
protected:
int m_n;
};
A::A(int n) : m_n(n){ };
The last line that defines the constructor A(n) seams to be equivalent to
A::A(int n){m_n=n; };
Is there any difference between the two lines in this or other circumstances?
What is the logic/origin of the first definition?
Daleth,
although there are several differences between the two versions of the code above, the most unusual to me is the implementation of the function outside the parenthesis
: ... {}
versus
{...}
Daleth,
thanks a lot. I think I understand it in part.
First, here is a part I understand best illustrated by the following example.
In the following code the constructor of B will be called twice, first the default one then the one with an integer parameter.
On the other hand, if I define the constructor A(int ) using initialization list as follows
A::A(int k) : b(k){};
I can eliminate the call to the default constructor B().
Here is the part I don't understand, yet.
Suppose the class A contained two or more objects that needed initialization, say B and C.
How can I use the initialization list to avoid using their default constructors?