non-const-non-primitive field in a const method

As stated on P215 [[effSTL]], inside const methods, all fields act like const fields. This is simpler for primitive fields like an int field, but trickier for non-primitive fields … like Animal —

class C{
Animal f;
Animal const & dump() const;
}

Inside dump(),
– we can’t overwrite f like “f = anotherAnimal”
– we can’t call mutator methods on f like “f.grow()” — uncompilable
– we can’t remove the “const” from dump() return type — uncompilable in GCC. See also http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.11 A common IV quiz.
– if Animal class overloads method age() on const, then compiler will statically bind the “f.age()” to the const version.

All these rules are compiler-enforced. No such check at run-time.

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