- Defining as const, a member function that calls a non-const member function of the class on the same instance of the class
What is the meaning of the above sentence? Can anybody please explain it with an example?
- Defining as const, a member function that calls a non-const member function of the class on the same instance of the class
What is the meaning of the above sentence? Can anybody please explain it with an example?
What is the context? Is this sentence preceded by "The following are errors"?
- Following are compilation errors
- Defining as const, a member function that modifies a data member of an object
- Defining as const, a member function that calls a non-const member function of the class on the same instance of the class
- Invoking a non-const member function on a const object
In this case, the "const" after "constMethod()" tells the compiler and all code that this method is guaranteed not to modify "this" instance of the class. "nonConstMethod()" does not make that guarantee.Code:class CompilationError { void nonConstMethod(); void constMethod() const { nonConstMethod(); } // can't do this };
"constMethod()" cannot guarantee that "this" instance will not be modified by "nonConstMethod()", so it's a compilation error to call "nonConstMethod()" from "constMethod()".
It's very similar to passing a pointer to const something to a function that takes a pointer to non-const something:
Code:void mightModifyFoo(Foo *); void doesNotModifyFoo(const Foo *foo) { mightModifyFoo(foo); // can't do this }