2

Well for example I have a map class which has some members: sizeX, sizeY, vector of tiles, name etc.

There are 2 basic approaches of managing its variables which are accessed from outside:

  • encapsulation, but it adds a lot of code and more typing (setX() and getX() const functions)
  • have the variables which are often accessed from outside as public members and keep it easy

I like neither of these. I came up with an idea: a class member, which from outside acts as const (so you can access it easily object.member but it's safe) and inside the class it is non-const. However, as far as I know c++ lacks it. The only (ugly) workaround I know is to have everything const and use const cast inside class functions.

Is there better approach for this in C++ 11? Is there a keyword for it?

user1873947
  • 1,781
  • 3
  • 27
  • 47
  • 1
    Not answering your question, but if you have a private member X_ and a public member function X(), that's only 2 extra characters to type for external users and one character for internal uses in the class (plus a one-line definition of X()). The less you save, the harder it will be to change things. Sounds like it could be convenient though. – Marc Glisse Jan 23 '13 at 18:55
  • 1
    Public `const&` to the private member should work, but that won't save you much typing (and it looks odd). – Mat Jan 23 '13 at 18:56
  • 1
    @Marc Glisse that's another idea (just short the typing), but 50 variables means 50 functions, it's not that rapid development. However, it seems to be a solution I think. – user1873947 Jan 23 '13 at 18:57
  • If you do that for 50 functions, I'd just write a macro to help with it, then I could just write: `MEMBER(int,x)`. – Marc Glisse Jan 23 '13 at 18:58
  • @Marc Glisse Oh yes, macro. I think you can make an answer with that. – user1873947 Jan 23 '13 at 18:59
  • 2
    Sounds like you are stumbling across the concept that is called properties; of which, the class can use to allow public non-modifying access but internally private modification. C++ does not support this natively, but there are several ways to emulate this functionality. – dans3itz Jan 23 '13 at 19:03
  • @dans3itz exactly this. Could you tell me something about emulating this in c++? – user1873947 Jan 23 '13 at 19:04
  • http://stackoverflow.com/questions/5772480/portability-of-native-c-properties || Question displays a MSVC extension; answers provide ideas for portability – dans3itz Jan 23 '13 at 19:08

1 Answers1

3

A simple workaround to just reduce slightly the amount of typing:

#define MEMBER(T,x) \
  private: T x##_; \
  public: T const& x () const { return x##_; }

struct A {
  MEMBER(int,x)
  MEMBER(double,y)
};

then you can use x_ and y_ inside the class and x() and y() outside.

Marc Glisse
  • 7,550
  • 2
  • 30
  • 53
  • I'll go with it. And I will also add setX(T) function to the macro when it is really needed to change from outside, but this will be done explicidly. – user1873947 Jan 23 '13 at 19:10