Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On a nonconst object, why won't C++ call the const version of a method with public-const and private-nonconst overloads?

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?

like image 483
japreiss Avatar asked Aug 14 '14 20:08

japreiss


People also ask

Can an object be const C++?

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.

What will happen if a const object calls a non-const member function?

Since we can't call non-const member functions on const objects, this will cause a compile error.

Can const methods be used by non-const objects?

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.

Can a const reference refer to a non-const object?

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 .


1 Answers

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.

like image 81
juanchopanza Avatar answered Sep 22 '22 05:09

juanchopanza