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

Updating a variable in a struct

So I just created a struct that makes a rectangle. the struct itself look likes this

    struct _rect
{
    //bottom left vertex
    int x = 0;
    int y = 0;

    // width and height 
    int width = 0;
    int height = 0;

    //top right vertex
    int y2 = y + height;
    int x2 = x + width; 
};

//init rect
_rect rect01;
rect01.x = rect01.y = 50;
rect01.width = rect01.height = 200;

in the main cpp when I want to create an instance of it I just want to enter bottom left x and y, plus width and height and I want it to calculate top right vertex by itself, is there a way to assign x2 and y2 their values without manuly doing so ?

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 should create a specific class:

class Rect
{
public:
  Rect(int x, int y, unsigned int width, unsigned int height)
  : x(x), y(y), width(width), height(height)
  {};

  int x() { return x; };
  int y() { return y; };
  int top() { return y + height; };
  int right() { return x + width; };

private:
  int x;
  int y;
  unsigned int width;
  unsigned int height;
}

That give you the possibility to do the computation you need in the class methods.
You can also create setters and more getters if you want.

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