Thursday, 15 August 2013

Are there two types of member initializer lists in C++?

Are there two types of member initializer lists in C++?

I saw two different ways to use member initializer lists. The first one is
like that:
class ClassName {
public:
arg_type_1 varName1;
arg_type_2 varName2;
// Constructor.
ClassName(arg_type_1 arg_name_1, arg_type_2 arg_name_2)
: varName1(arg_name_1), varName2(arg_name_2)
{
}
}
What is happening there is clear. In the constructor we have a list of
arguments and we use them to initialize members of the class. For example
arg_name_1 is used to initialize value for the varName1 variable of the
class.
Another way to use the member initializer appears in the case of inheritance:
class ChildClass : public ParentClass
{
ChildClass(string name) : ParentClass( name )
{
// What can we put here and why we might need it.
}
};
What happens here is also clear. When we call the constructor of the
ChildClass with one string argument, it calls the constructor of the
ParentClass with the same string argument.
What is not clear to me, is how compiler distinguish these two cases (the
syntax is the same). For example, in the second example, compiler might
think that it needs to take value of the name variable and assign it to
the ParentClass variable of the ChildClass and then it sees that such a
variable is not declared in the ChildClass.
The second unclear point to me is why we might want to put some content in
the body of the constructor from the second example. Even of there is
nothing it already creates and returns an object using the constructor of
the parent class.

No comments:

Post a Comment