Why do I need member initializers?What the real importance? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why do I need member initializers?What the real importance?

Why I need to initialize the constant variable using member initializers whereas I can initialize it where I declared the constant variable.Likewise the given example: #include <iostream> using namespace std; class MyClass { public: MyClass(int a); private: int regVar; const int constVar=5; }; MyClass::MyClass(int a) { regVar=a; cout << regVar << endl; cout << constVar << endl; } int main() { MyClass obj(42); } Output: 42 5 So,why do I need member initializers,If anyone knows do reply plz.Or it just an alternative way of initializing const variable?

1st May 2020, 6:44 AM
Golam Rabby
Golam Rabby - avatar
6 Answers
1st May 2020, 7:25 AM
HonFu
HonFu - avatar
+ 2
It's just another way to initialize your members since C++11. https://en.cppreference.com/w/cpp/language/data_members Scroll down to 'member initialization', and then the 2nd option.
1st May 2020, 7:23 AM
Dennis
Dennis - avatar
0
Hadia [ Gone Heartless ] I had done that lesson -_-
1st May 2020, 7:00 AM
Golam Rabby
Golam Rabby - avatar
0
Hadia [ Gone Heartless ] Have u seen my given example,it is initialized.
1st May 2020, 7:06 AM
Golam Rabby
Golam Rabby - avatar
0
Hadia [ Gone Heartless ] tnx for co-operation.-,-
1st May 2020, 7:23 AM
Golam Rabby
Golam Rabby - avatar
0
Dennis tnxs
1st May 2020, 7:24 AM
Golam Rabby
Golam Rabby - avatar