casting struct with pointer to const

I have a struct containing a pointer, and I want to pass it to a function such that the function can't modify the contents of the pointer. For example,
1
2
3
4
struct mystruct{
  int v;
  int* p;
};

Certainly I can cast to a "const mystruct", eg

1
2
3
mystruct a;
const mystruct& b=a;
b.v=3; // not allowed! 


and this prevents modification of b.v and b.p, but not *b.p. How do I cast it to make everything const? ie how do I cast it to something like this?

1
2
3
4
struct myconststruct{
  const int v;
  const int* const p;
};


With encapsulation. For example, make it a class and use getter/setters. Then you can make them const correct, and pass the object by const reference.
I see, thanks.
Using private members is a good solution, but I was wondering what you mean by "make them const correct"?
Disclaimer: not tested. :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class T {
    int n_;
public:
    int getN() const { return n_; }
    void setN( int n ) { n_ = n; }
};

T a;
cout << a.getN(); // ok
a.setN( 1 );      // ok

const T b;
cout << b.getN(); // ok
b.setN( 1 );      // error: discards qualifiers or something like that... 

Last edited on
Topic archived. No new replies allowed.