0

Error: uninitialized const member in constructor

When I run the program, it notifies: ..\Playground\: In constructor 'MyClass::MyClass()': ..\Playground\:15:1: error: uninitialized const member in 'const int' [-fpermissive] MyClass::MyClass() ^~~~~~~ ..\Playground\:12:14: note: 'const int MyClass::constVar' should be initialized const int constVar; I want to know, Why did this program come to this error? I removed constructor: MyClass::MyClass() then the program runs normally. Please see more: https://code.sololearn.com/ctCTbkR7IW0R/#cpp

18th Apr 2018, 4:46 AM
ThiemTD
ThiemTD - avatar
6 Réponses
+ 4
You've declared constVar as a constant member variable, but you haven't set it during initialisation. As it can't be set later, as it's constant, the compiler complains. const int constVar = 5; OR int constVar will solve your problem. Although I imagine you want the former.
18th Apr 2018, 4:55 AM
Emma
+ 4
To try to answer the question, I suppose it was because MyClass() constructor doesn't provide any means to initialize the "constVar" constant member, while we know clearly that a constant needs to be initialized, see here (constructor initializer chapter): https://www.sololearn.com/learn/CPlusPlus/1896/ On the other hand, the MyClass(int a, int b) has constructor initializer that assigns a value for "constVar" constant, which prevents the "uninitialized constant" error from happening, because the constant is being initialized in there. It would be better to have the constant initialized if the MyClass() constructor is used (e.g. const int constVar = 5), or you can add constructor initializer in MyClass() just to initialize the constant, as follows: MyClass::MyClass() : constVar(constDefVal) { cout << "Constructor" << endl; } Where "constDefVal" is the value you want to initialize constVar constant with, you decide the default value, as that constructor accepts no argument. I hope I explained it right, if I was mistaken please correct me, so I can fix the answer : ) Hth, cmiiw
18th Apr 2018, 8:06 AM
Ipang
+ 2
Yes, thanks for your answer. I know that, but I want to know exactly why is it reporting an error when I declared constructor MyClass(); Because if I don't declared the constructor, only MyClass::MyClass(int a, int b) then it runs normally.
18th Apr 2018, 6:09 AM
ThiemTD
ThiemTD - avatar
+ 2
Hi Ipang, Thanks a lot. I understand that this error is occurred becasue if constructor MyClass::MyClass() is used then program it see constVar is not initilized. I am clear.
18th Apr 2018, 8:41 AM
ThiemTD
ThiemTD - avatar
+ 2
@ThiemTD, You're welcome, glad if it helps : )
18th Apr 2018, 8:46 AM
Ipang
0
Ipang Great answer ☺ You have a knack for explaining things clearly.
18th Apr 2018, 11:02 AM
Emma