0

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;
Ants Aus
  • 45
  • 7

1 Answers1

5

Use member initializer list:

struct point
{
    const int x;
    const int y;

    point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302