particular access to class members

Hello everyone,

I have a question for you.

Imagine I have the following class

class My_Class
{
// declaration of public members
public :
int val_1 ;
int val_2 ;
.
.
.
.

// constructor
My_Class(int val_1, int val_2, ...) ;
};


We all know that val_1 and val_2 and all other members are here public and therefore can be access (read and modified) from outside the class.

If I change these to private, they will not be accessible at all from outside the class.

However, I would like to define all of them such a way that
1 - they can be read and modified from inside the class
2 - but they can be "read only" from outside the class. They somehow appear as const int from outside the class.


Of couse, it is possible to define the methods get_var_1(), get_var_2(), ... and so on, that would be define as

int My_Class :: get_var_1()
{
return var_1 ;
}


However, I don't want to define a method for each of the variable. I can have a lot of them.

What solution do I have ?

Thanks


Look up accessor methods.

1
2
3
4
5
6
7
8
9
10
11
12
class A {
   int a;
   double b;
   char c;
   ...

 public:
   int getA() const { return a; } //notice it returns a copy, not a reference
   double getB() const { return b; }
   char getC() const { return c; }
   ...
};
Last edited on
C++ does not allow this.

The closest you could get would be something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class My_Class
{
private:
  struct Data
  {
    int val_1;
    int val_2;
  } data;

public:
  const Data& Get() const { return data; }
};

// accessing outside of the class

int main()
{
  My_Class foo( ... );

  cout << foo.Get().val_1;  // OK
  cout << foo.Get().val_2;


  foo.Get().val_1 = 5;  // ERROR
}
Topic archived. No new replies allowed.