newbiecpp wrote:
> I have a simple class:
>
> class Point {
> public:
> Point() : xval(0), yval(0) {}
> Point(int x, int y) : xval(x), yval(0) {}
You mean
Point(int x, int y) : xval(x), yval(y) {}
>
> private:
> int xval, yval;
> };
>
> The Point is the member of another class:
>
> class UP {
> public:
> UP() : u(0) {} // line 1
> UP(int x, int y) : p(x, y), u(0) {}
It is generally recommended to keep the order of initialisers in the
list the same as the actual order of initialisation:
UP(int x, int y) : u(0), p(x, y) {}
to avoid potential confusion. It doesn't change anything, really,
just promotes good practice.
>
> private:
> int u;
> Point p;
> };
>
> My question is:
>
> 1) How member object is constructed (in this case, Point p)? Does the
> compiler initializes member object, then calls constructors, or member
> objects are initialized by constructors?
Yes. Memory is allocated, then a constructor is called with arguments
that you provide in the initialiser that corresponds to that member.
>
> 2) If member objects are initialized by constructors, does the code in line
> 1 should be:
>
> UP() : p(), u(0) {} or UP() : p, u(0)
>
> if line 1 is correct, how p is initialized?
If 'p' is missing from the initialiser list, but it's a class object
and it has its own default constructor, then it's default-initialised.
If 'p' didn't have the default constructor, but had the parameterised
one, the program would be ill-formed. If 'p' were a POD, it would be
uninitialised (if missing from the initialiser list).
Victor
|