+ 1

C++ Tutorial - More On Classes - Member Initializers

I'm a little confused with the examples on two of the pages here. This is the example given on the Second Page, which looks like it belongs in the Header file. class MyClass { public: MyClass(int a, int b) : regVar(a), constVar(b) { } private: int regVar; const int constVar; }; ----------------------------------------------------------------- Then on the Third Page, the example given is: MyClass.h class MyClass { public: MyClass(int a, int b); private: int regVar; const int constVar; }; ----------------------------------------------------------------- MyClass.cpp MyClass::MyClass(int a, int b) : regVar(a), constVar(b) { cout << regVar << endl; cout << constVar << endl; } Why has the " :regVar(a), constVar(b)" seemingly moved? In case anyone needs a link to the full pages: https://www.sololearn.com/Play/CPlusPlus/

11th Jun 2017, 10:46 AM
Cristian Chen
Cristian Chen - avatar
2 Respostas
0
answer is student, regVar and <<.
13th Jan 2020, 11:51 AM
Imanuel Wicaksono
Imanuel Wicaksono - avatar
- 1
1. The constructor definition is in the declaration. 2. The class only has functions declarations, so you can write their definitions separatedly. In a declarations you could write only the id and parameters' type, in a definition you need to specify paramaters' name ( and constant definition )
11th Jun 2017, 11:54 AM
Andrés04_ve
Andrés04_ve - avatar