Initializing a class member of a class

I have been looking through books and google for the past 30min. What they have to offer come painfully closed to what I seek, but not quite...

Thus I request your wisdom :)


The question is: if class A has a class B object as a member, how should I code the ctor of A, such that it calls a specific version of ctor of B?


A highly simplified example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Point
{
    private:
       double x;        // a point on the x-y plane
       double y;

    public:
       Point(const double a = 0, double int b = 0): x(a), y(b){};

// this ctor sets the coordinates (x, y) to the input values (a, b)

};


class Line
{
    private:
       Point begin;   // a line has two ends
       Point end;

       ....
}



I want to have a ctor for Line, which accepts four coordinates, calls the two-parameter ctor of Point, which in turns properly initializes Line::begin and Line::end.


How exactly do I do it?
With the initializer list. Exactly the same way you are initalizing Point's x and y:

1
2
3
4
5
6
7
8
class Line
{
//...
  Line(double x, double y, double x2, double y2)
    : begin( x, y )
    , end( x2, y2 )
  {}
};
Disch:

Thanks! That's what I kind of suspect, but everything I read so far stops short before spelling this out.

I want to to be absolutely sure. So the syntax here begin(x, y) means:

1) calling the ctor of Point for begin,
2) and then pass x, y as arguments to the ctor

Is this correct?
Yes, that is correct.
Then the ctor for end is called passing x2 and y2.
Topic archived. No new replies allowed.