coolVick
coolVick

Reputation: 538

Behavior of a compiler for a const member variable in a class

When a const member variable is defined/declared in a function or globally, storage may or may not be assigned to the variable depending on the use of it. e.g. if we are using "extern" for providing the variable an external linkage, then compiler is bound to assign storage to the variable. Otherwise compiler will keep it in symbol table. Now when a const member variable is declared in a class like this:

class myClass {
    const int myInt = 100;
}

In this situation, where does the compiler keep it?

Another question related to this which instantly came to my mind, should we declare it as private or protected?

Upvotes: 0

Views: 79

Answers (1)

juanchopanza
juanchopanza

Reputation: 227478

The meaning of const in this context is different. It doesn't mean that myClass::myInt is a compile time constant, it means it cannot change during the lifetime of a myClass object. You can still pick its value at runtime. Other than that, it is just like a non-const data member.

For example:

struct myClass {
    myClass(int i) : myInt(i) {} // needed for brace initialization pre-C++14
    const int myInt = 100;
};

int main()
{
  int n;
  cin >> n;
  myClass c{n};
}

So the compiler doesn't have the same freedom to perform optimizations as with a compile time constant.

In this situation, where does the compiler keep it?

Wherever it keeps the myClass instance the member belongs to, just like with any data member.

Another question related to this which instantly came to my mind, should we declare it as private or protected?

That is a matter of opinion and has nothing to do with const data members.

Upvotes: 1

Related Questions