Class protection classifications

Mar 15, 2014 at 1:52pm
Is there a way to make the Height property of CELL in the code below act in a way that allows the programmer to access Height without changing it?

I've tried protected, public, and private. Public allows the user to access the variable 'Height', however it also allows them to change the variable. I only want them to be able to access it similar to a function that returns a value, but without changing it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CELL{
private:
  int Height;
};

class grid{
public:
  std::vector<CELL> cell;
};

void DoStuff()
{
  grid g;
  int Height = g.cell[0].Height;
}
Mar 15, 2014 at 2:12pm
use (static) const. But you have to initialize it.

const int Height = 5;

or
static const int Height = 5;
Mar 15, 2014 at 2:18pm
Thanks, that's what I was afraid of. Based on grid properties I'll add later, the Height would have to be a variable that changes. I don't want the user to be able to change the cell dimensions directly, instead being done through the grid class.

For example...

1
2
3
4
class grid{
  void BuildGrid(int rows, int columns, int gridWidth, int gridHeight);
};


Based on the parameters sent to BuildGrid, the individual cell Heights would be calculated.
Mar 15, 2014 at 2:21pm
How about adding getter for that value?

Or you can google property class, but I would not recommend it.
Topic archived. No new replies allowed.