Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 460
Umal Stack Avatar asked Dec 18 '25 04:12

Umal Stack


1 Answers

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.

like image 155
Mohit Shah Avatar answered Dec 19 '25 23:12

Mohit Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!