reference field are writable even when host object is const

In the example below, the intVar field is a nonref and behaves as expected — can't be modified via a const method, and can't be modified via a variable marked const.

However the reference field this->intRef is not on the real estate of the host object and isn't part of the host object state, so in both cases above intRef is modifiable!

using namespace std;
template struct J{
    J(T & rhs):intRef(rhs){}
    void doIt(T a) const{
        this->intRef = a; // legal even when method is const and is called !
        //this->intVar = a; // illegal when method is const and is called
    }
    T & intRef;
    T intVar;
};
int main()
{
    int a=22;
    const J j1(a);
    j1.doIt(89);
    j1.intRef = 19; // legal even when object is const
    //j1.intVar = 19; // illegal when object is const
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s