Class constructors and composition vs generalization

Hey folks, I have a constructor for class Line2D that takes in 2 Point2D objects as arguments. My intention is to create 2 separate Point2D objects, before creating a Line2D object and pass in the Point2D objects to the constructor upon creation. However when I try to compile the code, it gives me an error because it apparently attempts to call a default constructor for Point2D that doesn't exist. I don't understand why it does this as Line2D is not a child class of Point2D; I understand how inheritance and constructors work but the relationship here is composition rather than generalization. How would I solve this problem? My code is below. Thanks for the help.

class Point2D
int x,y;

public: Point2D(int,int);

Point2D::Point2D(int ecks, int why)
x = ecks;
y = why;
class Line2D
Point2D pt1, pt2;

public: Line2D(Point2D,Point2D);

Line2D::Line2D(Point2D first, Point2D second)
pt1 = first;
pt2 = second;
Last edited on
Use initialisation lists in your constructors (more efficeint and avoids this problem)

Point2D::Point2D(int ecks,int why)
  : x(ecks), y(why)

Line2D::Line2D(const Point2D& first, const Point2D& second)
  : pt1(first), pt2(second)

this constructs the elements in place instead of calling default constructors for the contained objects and then assigning to them.

Topic archived. No new replies allowed.