Umal Stack
Umal Stack

Reputation: 241

The constructor initializer list and const variable

probably this might be a very basic question, but still wanna understand some basic concepts...

why do we define a variable as a const ? - to keep the value of that specific variable constant through out the program.

but, when i come across initialization list for constructors, that allows to assign value to the const variable during object construction( i tried the below program for ex.), i'm confused with the basic concept of const keyword itself. can someone clarify this?

what is the purpose of const variable in the following program, if it is allowed to change during object construction? do we have any real time scenarios for these kinda behavior? if so, can you please give some scenarios?

#include<iostream>
using namespace std;

class Test {
    const int t;
public:
    Test(int t):t(t) {}  //Initializer list must be used
    int getT() { return t; }
};

int main() {
    Test t1(10);
    cout<<t1.getT();
    return 0;
}

Upvotes: 3

Views: 7087

Answers (3)

Mohit Shah
Mohit Shah

Reputation: 862

Basically when data members are declared constant they have to have some value before the object is constructed Hence we use member initializer so that before the object is constructed the data member has some value.

in this program till the end the data member will have the same value

for real scenario:

For example you have to make a payroll program in which each employee has a first name and last name so you wouldn't want functions to accidentally modify their names so hence to prevent this you can keep them constant.

Upvotes: 6

alexrider
alexrider

Reputation: 4463

why do we define a variable as a const ?

A variable is declared const to indicate that it will not be changed.

but, when i come across initialization list for constructors, that allows to assign value to the const variable during object construction( i tried the below program for ex.), i'm confused with the basic concept of const keyword itself. can someone clarify this?

Is it not assignment but construction if it would be of not simple type but of MyClass, there constructor of MyClass would be used, not operator=

Upvotes: 0

bash.d
bash.d

Reputation: 13207

It does not change during the object-construction, because it has no (defined) value.
When you supply a const-member in a class, then this is a part of the object's identity and this particular value will stay the same through the object's life.
When declaring a member const you promise the compiler that you won't attempt to change the value of this member.

From MSDN

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

// constant_values1.cpp
int main() {
   const int i = 5;
   i = 10;   // C3892
   i++;   // C2105
}

Upvotes: -1

Related Questions