reference function const

Hello Forum,

See the following code:

class A
{
public:
int intValue = 3;
// int & rValue1() const { return intValue; } // Not allowed.
int & rValue2() const { return (int &) intValue; }
}

#1: Why is 'rValue2()' allowed? At 'rValue1()' it is telling me that it is not allowed, and then I do the same at 'rValue2()'?

#2: 'rValue2()' is a const function that does not have the rights to grant write-access to a member variable. But "(int &)" is a form of 'type casting' that overrules this?

Thank you.
Last edited on
In the const-qualified member function,
the expression intValue is an lvalue of type 'const int'
the expression (int &)intValue is an lvalue of type 'int' (the lvalue reference cast casts away the constness)
Last edited on
Ok, thanks for the reply.
Topic archived. No new replies allowed.