1

I want to make a class/struct where one of the attributes is functionally dependent on other attributes. How can this be achieved?

struct Numbers {
  int a;
  int b;
  int c; // c == a+b
}


Numbers n1 {1, 2, 3}; // Ok.
Numbers n2 {1, 2, 4}; // Error! 

In my use case, a, b, c are constant, if that matters (so const int may be used).

All attributes will appear many times in class/struct methods, so the goal is to cache the value a+b. Addition is used as an example, the dependency function may be more complex.

Frank Vel
  • 1,202
  • 1
  • 13
  • 27

2 Answers2

5

If a and b are mutable then you can't enforce that c is kept in sync; all three would have to be const for you to enforce this invariant.

The simplest approach would be to make c a function:

struct Numbers {
  int a;
  int b;
  int c() const { return a + b; }
}

If you want the value of c to be cached instead of computed when needed then you need to hide a and b behind accessors as well so that you can update c when they are updated.

class Numbers {
public:
  Numbers(int a, int b) : ma{a}, mb{b} { updateC(); }

  int a() const { return ma; }
  int b() const { return mb; }
  int c() const { return mc; }

  void a(int v) { ma = v; updateC(); }
  void b(int v) { mb = v; updateC(); }
  // No setter for c

private:
  void updateC() { mc = ma + mb; }

  int ma;
  int mb;
  int mc;
};
cdhowie
  • 158,093
  • 24
  • 286
  • 300
2

You can do something like that:

struct Numbers {
    Numbers(int a, int b) : a(a), b(b), c(a + b) {}

private:
    int a;
    int b;
    int c; // c == a+b
};

Edit:
To keep the values of a and b updated, and to get the values of those variables, you'll have to use get & set methods, like in @cdhowie response.

Coral Kashri
  • 3,436
  • 2
  • 10
  • 22