0

(This is not a question about overloading operator. in general.)

We know that there are many good reasons to use setter and getter methods.

Well, then, it seems strange to me these are not customization points of member access i.e. if class A has a data member x, then the use of x in an lvalue context will not really just use x, but rather call some method (say A::get_x_lvalue(), never mind the syntax) which defaults to

typename std::add_reference<decltype(x)>::type A::get_x_lvalue() {  return x; }

and can be implemented as an override, and similarly when x is used in a prvalue constant will call an overridable

decltype(x) A::get_x_prvalue() const { return x; }

... analogously to, say, how you do this in Javascript.

My question are:

  • Historically, why was this not added to the language along with customizable copy constructors, assignment operators and destructors?
  • Has something like this been officially proposed? If so, what's its status or why was it rejected?
  • Are there significant detriments to such a scheme, other than: 1. Slower compilation and 2. Not being able to "trust" the period in my_a.x to be just a plain access?
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 6
    " there are many good reasons to use setter and getter methods" - even more not to. –  Mar 04 '18 at 22:04
  • Are you asking why there aren't properties in C++? – Matteo Italia Mar 04 '18 at 22:05
  • 1
    @NeilButterworth: There are also many good reasons not to implement a copy constructor, assignment operator, move ctor, move assignment and dtor... – einpoklum Mar 04 '18 at 22:05
  • @MatteoItalia: I guess you could phrase the question that way; but I'm being specific, i.e. I'm asking why _historically_, and also what are the detriments of this being allowed. – einpoklum Mar 04 '18 at 22:06
  • 3
    You _never_ absolutely need getters and setters (they are a design feature), but C++'s value-based types will _often_ need the functions you mention. –  Mar 04 '18 at 22:08
  • 2
    Most types need to be instantiated and destructed. Most types do not need direct access to their data members via member functions. – juanchopanza Mar 04 '18 at 22:18
  • 2
    Setters and getters, if they give access to a data member, are a failure of encapsulation. So making that easy would not be a good move. Setting and getting a *property* of a type, without the requirement of a matching data member, is a different matter. Your question seems to be focused on the anti-pattern version. – juanchopanza Mar 04 '18 at 22:22

0 Answers0