c++object

How do I delegate this constructor?


For an c++ assignment I need to work with a Point class and with that Point class I need to make a Triangle class.

I used the following constructors for the Point class:

//constructor 1
Point() 
{
    x = 0;
    y = 0;
}

//constructor 2
Point(double i, double j)
{ 
    x = i; 
    y = j;
}

My first constructor for the Triangle class is:

  Triangle()
    {
        a = Point();
        b = Point();
        c = Point();
    }

Now the next step is:

Create a constructor that takes three Point arguments and initialises attributes a, b and c with the three arguments. Use constructor delegation for the initialisation of the attributes.

I read that you need you use constructor delegation in order to delegate work that is already done to the new constructor in order to prevent rewriting code.

  Triangle(Point a, Point b, Point c)
        {
         
        }

I'm a beginner and I find it really hard to make a new class with an already existing class. Could I please get feedback on how I could delegate this constructor?

Tim


Solution

  • Here's a slightly refactored version of your code that reflects more modern C++ practice (since 2011):

    struct Point {
        Point() = default;
        Point(double i, double j) : x(i), y(j) {}
    
        double x = 0;
        double y = 0;
    };
    
    struct Triangle {
        Triangle() = default;
        Triangle(Point i, Point j, Point k) : a(i), b(j), c(k) {}
    
        Point a, b, c;
    };
    

    This doesn't use the "constructor delegation" feature you mentioned because that applies to constructors calling other constructors of the same class. It uses initialization lists and class member initializers (= 0) to make the code more concise and idiomatic (by being able to use the = default declarations for the default constructors, rather than having to write them ourselves).

    If you really wanted to use constructor delegation for Point, you'd write the default constructor like this instead:

    Point() : Point(0, 0) {}
    

    And then you wouldn't need the = 0 for x and y.