Search code examples
c++functionclassmember-functionsfunction-qualifier

Const Class and member functions


Do you need to define const functions when you want to create a new const instance of a class?

Somehow my compiler dont find the "regular" (not const) functions, when i try to access them from a const class instance.


Solution

  • Yes, if an object is const, you can only call const functions on that object.

    If a function is not marked const, the compiler must assume that it is allowed to change the members of the class. And since you can't change the members of a const class instance, you cannot call non-const functions on that instance either.

    Note that the opposite case is different - there is no problem calling const functions on non-const objects. Therefore it is recommended to always mark member functions as const wherever it makes sense to do so. It is important to mark function parameters, reference variables, etc. as const for many of these same reasons. The community typically refers to this practice as maintaining "const correctness."