How to create a struct constructor which assigns values to constant struct parameters?

  c++, constants, constructor, struct

I’m trying to create a structure (or class, doesn’t matter) whose constructor assigns values to the struct’s constant parameters. I.e I don’t want to change any variables of a Point object after its creation.

Following code obviously doesn’t work, because the constructor tries to change the value of a constant.

struct point
{
    const int x;
    const int y;

    point(int _x = 0, int _y = 0)
    {
        x = _x;
        y = _y;
    }
};

point myPoint = point(5, 10);
std::cout << myPoint.x << myPoint.y << std::endl;

Source: Windows Questions C++

LEAVE A COMMENT