Reputation: 3775
Here are the following code:
#include <iostream>
using namespace std;
class A {
public:
int *x;
};
int main() {
int b=100;
A a;
a.x = &b;
const A &m = a; // clause 1 - Is this top-level const?
int *r = m.x; // *r has no const yet allowed. Is it due to reference m being top level const?
}
Any help appreciated.
Thanks
Upvotes: 0
Views: 141
Reputation: 75697
int const ca = 24;
int a = ca;
You would expect this to compile right? And indeed it does. Here I initialized a integer with the value 24
.
You code is the same situation, except that instead of integer you have pointer to integer:
m
is const so m.x
is const. The x
is const, i.e. x
cannot be modified (via m
). In stricter terms m.x
is of type int * const
i.e. constant pointer to integer.
int *r = m.x
Here you just initialize the pointer r
with the value of the pointer m.x
. The fact that m.x
is const is not an issue. Both types without their top level cv are identical: pointer to (mutable) integer.
const A &m = a; // clause 1 - Is this top-level const?
Yes Talking about top level const on references is strange indeed. A reference cannot be rebound. However if we are talking about the referenced type, i.e. const A
then yes, it is top level. But then again talking about top level const is useful only on pointer types. E.g. int *const cp
vs const int *p
.
Upvotes: 2