Search code examples
c++structconstructorphysics

Why is my struct constructor, which contains other structs, not working?


I'm trying to create a basic physics' simulation that calculates rectilinear movement. When I tried to add a constructor to the Body struct, it showed the following error:

no matching function to call to 'Vector::Vector()'

Here's the code:

struct Point{
    int x,y;
    Point(int _x, int _y) : x(_x), y(_y)
    {
    }
};
struct Vector{
    int value, direction;
    Vector(int _value, int _direction) : value(_value), direction(_direction)
    {

    }
};
struct Body{
    std::string ID;
    int m;
    Vector v, a;
    Point pos;

    Body(std::string _ID = "NONE", int _m = 0, Point _pos = Point(0, 0))
    {
        ID = _ID;
        m = _m;
        pos = _pos;
        v = Vector(0, 0);
        a = Vector(0, 0);
    }
};

I don't have the slightest idea why this is happening. I just figured out if I declare pos before v and a, the error replaces 'Vector' with 'Point'. Also, the constructor works perfectly without declaring any of those variables. It's probably a very dumb overlook. Help.


Solution

  • Members are initialized before the constructor body is executed. Hence, the constructor body is the wrong place to initialize members. Use the member initialization list instead:

    Body(std::string _ID = "NONE", int _m = 0, Point _pos = Point(0, 0))
    : ID(_ID), m(_m), v(0,0), a(0,0), pos(_pos) {
    }
    

    In your code, because you did not specify an initializer for the members, they were default initialized before the constructor body runs. But Vector has no default constructor.

    Note that members are initialized in the order they are listed in the class. Typically compilers warn when the order in the initializer list is different.