Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override the default behavior of getting a struct member in C++?

Similar to the @property tag in python, I am trying to figure out if it is possible to override the behavior of a getter in c++ without having to make a function call.

Basically, is it possible to do the following in c++:

class vector2(class):
    def __init__(self):
        self.values = [1,2]

    @property
    def x(self):
        return self.values[0]
pos = vector2()
my_var = pos.x

Is the best solution to just write getters and setters?

like image 262
Saucy Dumpling Avatar asked Jan 17 '26 11:01

Saucy Dumpling


1 Answers

The short answer is no, you can't do that.


For a 2D vector that you can access as an array, I would do something like this:

struct Vec2 {
  float x;
  float y;

  const float &operator[](const size_t i) const {
    static_assert(sizeof(Vec2) == 2 * sizeof(float));
    assert(i < 2);
    return (&x)[i];
  }

  float &operator[](const size_t i) {
    return const_cast<float &>(std::as_const(*this)[i]);
  }
};

So you can access the member variables directly or use the overloaded subscript operator.

Vec2 v{4, 5};
v.x += 9;
v[1] = -3;

In general, getters and setters are called explicitly. A naming convention I've seen quite a lot of is giving the getter and setter the same name.

class Foo {
public:
  int member() const {
    return hidden;
  }

  void member(const int value) {
    hidden = value;
  }

private:
  int hidden;
};

This naming convention makes access very clean but still makes it clear that a function call is taking place.

Foo f;
f.member(5);
int five = f.member();
like image 122
Indiana Kernick Avatar answered Jan 20 '26 00:01

Indiana Kernick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!