user1873947
user1873947

Reputation: 1811

Class member - const for the outside world, non-const for the class

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:

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?

Upvotes: 2

Views: 563

Answers (1)

Marc Glisse
Marc Glisse

Reputation: 7925

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.

Upvotes: 3

Related Questions