Transferred from: http://www.cnblogs.com/kaituorensheng/p/3477630.html
1. Class members are const types
2. Class members are reference types
#include <iostream>using namespace Std;class a{public : I (v), P (v), J (v) {} void Print_val ( {cout << "Hello:" << i << " << J << Endl;} Private: const int i; int p; int &j;}; int main (int argc, char **argv) { int pp = n; A b (PP); B.print_val ();}
The reason
A const object or reference can only be initialized but cannot be assigned a value. The function body of a constructor can only be assigned instead of initialized, so the only chance to initialize a const object or reference is in the initialization list before the body of the constructor function.
From scratch called initialization, initialization (call copy constructor) creates new object, assignment (call assignment operator) does not create new object, but assigns value to existing object.
3. Class Members are class types that do not have a default constructor
#include <iostream>using namespace Std;class base{public : Base (int a): Val (a) {} private: int Val;}; Class a{public : B (v) {} void Print_val () {cout << "Hello:" << p << endl;} Private: int p;
Base b;}; int main (int argc, char **argv) { int pp = n; A b (PP); B.print_val ();}
The same reason is that every member of a class member is initialized when the object is created
4. If the class has an inheritance relationship, the derived class must call the constructor of the base class in its initialization list
#include <iostream>using namespace Std;class base{public : Base (int a): Val (a) {} private: int Val;}; Class A:public base{public : A (int v): P (v), Base (v) {} void Print_val () {cout << "Hello:" << P << Endl;} Private: int p;}; int main (int argc, char **argv) { int pp = n; A b (PP); B.print_val ();}
Several scenarios in which "C + +" must be initialized in the class initialization list