I need to initialize an object nested 2 deep (using the object's constructor) but am not sure how. This is a simpler example of what I want to do:
suppose I have classes Point and Line:
class point
{
double x;
double y;
public:
point(double xx, double yy) x(xx), y(yy);
};
class line
{
point a;
point b;
public:
line(point aa, point bb) a(aa), b(bb);
};
Now I want to create a class drawing consisting of two lines, but I want to use point coordinates to describe the lines contained in the drawing:
class drawing
{
line sketch[2];
public:
drawing(???????????) ??????
};
What would my drawing constructor look like? Would I use the constructor from point?
(I do realize that this is not necessarily the ideal construct for points, lines, etc, but it illustrates my question. The actual application involves templates being passed as template arguments, but my question right now is much simpler.)
Thanks, elabelle
Presumably the constructor would take two lines as parameters, but you're going to either need to change line sketch[2] to something else or you need to write some default constructors (on line and point).
1 2 3 4 5 6 7
class drawing {
line line1;
line line2;
public:
drawing( const line& line1, const line& line2 ) :
line1( line1 ), line2( line2 ) {}
};
hmmm ... that's what I thought you'd say. I shouldn't have put the array there to confuse matters - that was an additional question I had - which you did answer - thanks.
But my bigger question arises from a solution to a programming exercise in the book I'm studying: C++ Primer Plus, by Stephen Prata. It appears that they use a constructor in a member initialzation list -- is this an option (other than in an inheritance situation)? The example is a bit complicated by the use of templates passed as template parameters and multiple typedefs so I'm not certain that this is what they are doing, and I can't find anywhere in the text that suggests this as a possiblity.
So, suppose I just have the point and line classes I listed. (Here again for convenience):
class point
{
double x;
double y;
public:
point(double xx, double yy) x(xx), y(yy);
};
class line
{
point a;
point b;
public:
line(point aa, point bb) a(aa), b(bb);
};
Could I use an alternative constructor for the line class as follows:
line(double x1,double y1,double x2,double y2) : a ( point(x1,y1) ), b ( point(x2,y2) ) {}