Junior — Middle
How can you set a value for an object declared with the const keyword?
sobes.tech AI
Answer from AI
In C/C++, the keyword const means that the value of an object cannot be changed after initialization. However, there are several ways to set the value for a const object:
- Initialization at declaration:
const int x = 10; // Value is set immediately
- Using a constructor for const class objects:
class MyClass {
const int value;
public:
MyClass(int v) : value(v) {} // Initialize const member via initializer list
};
const MyClass obj(5); // value is set through constructor
- Using pointers or references to non-const data (not recommended, as it violates const-correctness):
const int x = 10;
int* p = (int*)&x; // Type casting
*p = 20; // Undefined behavior, may lead to errors
Thus, for a const object, the value must be set during initialization — it cannot be changed later. If you need to change the value, the object should not be const.