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
CodePudding user response:
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