How to initialize 'const int var[5]' member of a class with 1,2,3,4,5? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to initialize 'const int var[5]' member of a class with 1,2,3,4,5?

Keep in mind it is 'const'

23rd Jun 2016, 12:15 PM
Jigar Thacker
Jigar Thacker - avatar
4 Answers
+ 6
A non static const array is cannot be initialize in constructor. Whereas you can initialize this from C++11 as shown below. class test { public: test () : var({1,2,3,4,5}) {} const int var[5]; }; in main () test obj; cout <<obj.var[0]<<obj.var[1]<<obj.var[2]<<obj.var[3]<<obj.var[4]<<endl; Hope you understand this otherwise let me know the exact scenario which you are trying to address.
23rd Jun 2016, 1:29 PM
Venkatesh(Venki)
Venkatesh(Venki) - avatar
+ 2
how will it work if i want pass its values from constuctor argument?
23rd Jun 2016, 1:34 PM
Jigar Thacker
Jigar Thacker - avatar
+ 2
Guess, in a same way it will work. Take an argument in constructor and assign it to the array test (arr) : var (arr){} but not sure whether will it or not. If not you can use the pointers instead of array.
23rd Jun 2016, 1:49 PM
Venkatesh(Venki)
Venkatesh(Venki) - avatar
+ 1
Thank you buddy. It works.. :)
23rd Jun 2016, 1:33 PM
Jigar Thacker
Jigar Thacker - avatar