Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ const member functions are modifying member variables

Today I found out that code like that works. That sounds really strange to me, because as far as I always knew you can't modify any of members from const member function. You actually can't do it directly, but you can call non-const member function. if you mark member function as const that means that this pointer passed to the function is pointing to const object, then how non-const member function is called in the example bellow?

#include <iostream>

class X
{
public:
    void foo() const
    {
        ptr->bar();
    }
    void bar() {}
private:
    X * ptr;
};

int main()
{
}
like image 682
axe Avatar asked Sep 12 '11 15:09

axe


People also ask

Can a const member function modify a const data member?

Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.

What are const member functions?

The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.

Which is the correct condition on const member functions?

5. Which is the correct condition on const member functions? Explanation: The const member functions are restricted to call any other non-const member functions. This is to ensure that the const function doesn't have any code that might modify the calling object.

Can member variables be const?

Avoid using the const keyword with member variables of a class or struct type. For a class type, if a piece of data is not supposed to change after being initialized, enforce this by design of the public API, not via the `const` key word. For a struct which is a "dumb aggregate", it isn't appropriate to use `const`.


2 Answers

Your member variable is not X, but pointer to X. As long as foo does not modify the pointer, it can be const.

like image 90
quant_dev Avatar answered Sep 19 '22 04:09

quant_dev


When you have a pointer member, then the pointer is const in a const method. You won't be allowed to change the address stored in the pointer. But you can change the pointee all you like.

It's the difference between

X* const cannot_change_pointer;  //this is how top-level const applies to pointers
const X* cannot_change_pointee;

What's even more interesting is that const on a method has no effect whatsoever on reference members for the same reason (a const method would only prevent you making a reference refer to something else which can't be done with a reference anyway).

like image 23
UncleBens Avatar answered Sep 23 '22 04:09

UncleBens