Sobes.tech
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:

  1. Initialization at declaration:
const int x = 10; // Value is set immediately
  1. 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
  1. 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.