In classes and objects when we use const keyword for a data member , we use constructor! I know that | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

In classes and objects when we use const keyword for a data member , we use constructor! I know that

question is why only constructor ? why const is intialized only with help of constructor? is there any other way if no, why not?

18th Sep 2018, 9:07 AM
Bunny
Bunny - avatar
1 Answer
+ 5
It helps if you understand what const is and means. const = constant. https://www.vocabulary.com/dictionary/constant -Think of something or someone that does not change as constant- A constant value has to be initialised with a value at the time of its creation because its value is constant and does not change. To answer your question though: You could set a const data members value with a hard coded value instead of setting it at initialisation, but that reduces flexibility. Here is an example https://code.sololearn.com/cbC2UcKGrXeF/?ref=app
18th Sep 2018, 9:23 AM
jay
jay - avatar