class C { public: void foo() const {} private: void foo() {} }; int main() { C c; c.foo(); }
MSVC 2013 doesn't like this:
> error C2248: 'C::foo' : cannot access private member declared in class 'C'
If I cast to a const
reference, it works:
const_cast<C const &>(c).foo();
Why can't I call the const
method on the nonconst
object?
When a function is declared as const, it can be called on any type of object, const object as well as non-const objects. Whenever an object is declared as const, it needs to be initialized at the time of declaration. however, the object initialization while declaring is possible only with the help of constructors.
Since we can't call non-const member functions on const objects, this will cause a compile error.
const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.
No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r .
The object is not const
, so the non-const
overload is a better match. Overload resolution happens before access checking. This ensures that overload resolution is not inadvertently changed by changing the access of a member function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With