What does the const keyword indicate when used in C++ function declaration?
Fujitsu aptitude question, verified with a worked answer. Free to practise - no sign-up.
What does the const keyword indicate when used in C++ function declaration? What does the const keyword indicate when used in C++ function declaration? © The function cannot be called - A) The function is a constructor. - B) The function does not modify the object it is called on. - C) The function is a destructor.
Show answer & explanation
In C++, when the 'const' keyword is placed after the parameter list of a member function, it designates the function as a 'const member function'. This guarantees that the function will not modify any non-static member variables of the object for which it is called.
Step-by-step Derivation:
Step 1: Analyze the syntax of a const member function: void MyClass::myMethod() const { ... }.
Step 2: Identify the effect on the this pointer. In a non-const member function of class T, the type of this is T* const (a constant pointer to a mutable object). In a const member function, the type of this becomes const T* const (a constant pointer to a constant object).
Step 3: Evaluate the constraints. Because this is treated as a pointer to a constant, any attempt to modify member variables (unless they are marked as mutable) or call other non-const member functions will result in a compilation error.
Step 4: Compare with options. Option A (constructor) and Option C (destructor) are special member functions that cannot be marked as const. Option B correctly describes the behavior of a const member function.