Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem accessing member of struct inside a class

I am making a battleship board game in c++ and have issues accessing the struct that I have declated inside one of my classes.

class Ship {
    typedef struct {
        int x;
        int y;
    }Start;
    typedef struct {
        int x;
        int y;
    }End;
    bool isAfloat;
    
    Start _start;
    End _end;

public:
    Ship(int start_x, int start_y, int end_x, int end_y);

I have tried to do in every thinkable way but I’m clearly missing something here.

Ship::Ship(int start_x, int start_y, int end_x, int end_y):
    _start.x(start_x), //error, expected "(" where the "." is 
    _start.y(start_y),
    _start.x(end_x),
    _end.y(end_y)
    {}

Any help appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to initialize the whole object directly, not their members separately. E.g.

Ship::Ship(int start_x, int start_y, int end_x, int end_y):
    isAfloat ( ...true_or_false... ), // better to initialize it too
    _start {start_x, start_y}, 
    _end {end_x, end_y}
    {}

BTW: Since C++20 you can use designated initializers then you can specify members’ name as:

Ship::Ship(int start_x, int start_y, int end_x, int end_y):
    isAfloat ( ...true_or_false... ), // better to initialize it too
    _start {.x = start_x, .y = start_y}, 
    _end {.x = end_x, .y = end_y}
    {}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading