- 2074 Asoj · 5 marks
Constant object and constant function
Short answer
A const member function promises not to modify the object's data and can be called by const objects; non-const functions cannot be called on const objects. Example: class Test with const get() and non-const set(); a const object t1 can call get() but not set(), while a non-const object can call both.
Explain the relation between constant object and constant function with example.
Constant member function
A member function declared with const after its parameter list promises not to change any data member of the object. The compiler gives an error if it tries.
int getValue() const;
Constant object
An object declared const cannot be modified after creation. Its data must be set by the constructor.
const Test t(10);
Relation
- A const object can call only const member functions (and constructor and destructor). Calling a non-const function on it is an error, since that function might modify the object.
- A non-const object can call both const and non-const functions.
- So const functions are the way to give read-only access to a const object. Functions that only display or return values should be made const.
Example
#include <iostream>
using namespace std;
class Test
{
int value;
public:
Test(int v) { value = v; }
int get() const // const function: cannot modify value
{
return value;
}
void set(int v) // non-const function
{
value = v;
}
};
int main()
{
const Test t1(10);
cout << t1.get() << endl; // OK: const function on const object
// t1.set(20); // Error: non-const function on const object
Test t2(5);
t2.set(8); // OK
cout << t2.get() << endl; // OK, const function on normal object
return 0;
}
Output
10
8
A mutable data member is the only member a const function may change.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Default arguments and function overloading · Object Oriented Programming, chapter 3 · asked 5×
- Pure virtual function and abstract class · Object Oriented Programming, chapter 7 · asked 5×
- Need of virtual function · Object Oriented Programming, chapter 7 · asked 4×
- Class and function template with syntax · Object Oriented Programming, chapter 9 · asked 4×
- Inline function: significance and limits · Object Oriented Programming, chapter 3 · asked 3×
- Static data member and member function · Object Oriented Programming, chapter 4 · asked 3×
- White noise: relation between PSDF and AC function · Communication Systems, chapter 9
- PSD–autocorrelation relation; stereo FM · Communication Systems, chapter 3
- Parseval's theorem; PSD–autocorrelation relation for white noise · Communication Systems, chapter 9
- R-H relation between K and T for stability · Control Systems, chapter 4