When do you need to use a list of initialization?

The initialization list is used to initialize the data of the class. The member list is initialized in the constructor, followed by the colon of the constructor.
Refer to the following example:

  1. #include<iostream>  
  2.   
  3. class Point  
  4. {  
  5. private:  
  6.     int x;  
  7.     int y;  
  8. public:  
  9.     Point(int i = 0, int j = 0):x(i), y(j) {}  
  10.     / * The above initialization list is optional because it can also be written as the following form: 
  11.         Point(int i = 0, int j = 0) { 
  12.             x = i; 
  13.             y = j; 
  14.         } 
  15.     */  
  16.     int getX() const {return x;}  
  17.     int getY() const {return y;}  
  18. };  
  19.   
  20. int main()  
  21. {  
  22.   Point t1(11, 22);  
  23.   std::cout<<”x = ”<<t1.getX()<<“, ”;  
  24.   std::cout<<”y = ”<<t1.getY();  
  25.   return 0;  
  26. }  
#include<iostream>

class Point
{
private:
    int x;
    int y;
public:
    Point(int i = 0, int j = 0):x(i), y(j) {}
         / * The above initialization list is optional because it can also be written as the following form:
        Point(int i = 0, int j = 0) {
            x = i;
            y = j;
        }
    */
    int getX() const {return x;}
    int getY() const {return y;}
};

int main()
{
  Point t1(11, 22);
  std::cout<<"x = "<<t1.getX()<<", ";
  std::cout<<"y = "<<t1.getY();
  return 0;
}
Output:
x = 11, y = 22

The above code is a simple presentation for the initial list. X and Y can initialize in the constructor.
However, in some cases, the data member cannot be initialized in the constructor, but only the initialization list can be used. These scenarios are listed below:

1) Non-static constant constant data member initialization:

Const data members must use initialization list. Refer to the member variable T in the following example.




  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class Test  
  5. {  
  6.     const int t;  
  7. public:  
  8.     Test(int t):t(t) {}  / / Must use initialization list  
  9.     int getT() { return t; }  
  10. };  
  11.   
  12. int main()  
  13. {  
  14.     Test t1(111);  
  15.     cout<<t1.getT();  
  16.     return 0;  
  17. }  
#include<iostream>
using namespace std;

class Test
{
    const int t;
public:
         TEST (INT T): T (T) {} // must use initialization list
    int getT() { return t; }
};

int main()
{
    Test t1(111);
    cout<<t1.getT();
    return 0;
}


Output:
111

2) Reference members' initialization:
Reference members must use the initialization list. Refer to 't' in the example below.

  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class Test  
  5. {  
  6.     int &t;  
  7. public:  
  8.     Test(int &t):t(t) {}  / / Must use initialization list  
  9.     int getT() { return t; }  
  10. };  
  11.   
  12. int main()  
  13. {  
  14.     int x = 22;  
  15.     Test t1(x);  
  16.     cout<<t1.getT()<<”, ”;  
  17.     x = 33;  
  18.     cout<<t1.getT()<<endl;  
  19.     return 0;  
  20. }  
#include<iostream>
using namespace std;

class Test
{
    int &t;
public:
         TEST (INT & T): T (T) {} // must use initialization list
    int getT() { return t; }
};

int main()
{
    int x = 22;
    Test t1(x);
    cout<<t1.getT()<<", ";
    x = 33;
    cout<<t1.getT()<<endl;
    return 0;
}

Output:
22, 33

3) Initializing member objects without the default constructor:
In the following example, the data member 'a' of class 'b' is an object of class 'a', and 'A' does not have the default constructor, then 'b' must use the initial list. To initialize 'a'.




  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class A  
  5. {  
  6.   int i;  
  7. public:  
  8.   A(int);  
  9. };  
  10.   
  11. A::A(int arg)  
  12. {  
  13.   i = arg;  
  14.   cout << ”A’s Constructor called: Value of i: ” << i << endl;  
  15. }  
  16.   
  17. // class B contains an object of A  
  18. class B  
  19. {  
  20.   A a;  
  21. public:  
  22.   B(int);  
  23. };  
  24.   
  25. B::B(int x) : a(x)   / / Must use initialization list  
  26. {  
  27.   cout << ”B’s Constructor called”;  
  28. }  
  29.   
  30. int main()  
  31. {  
  32.   B obj(10);  
  33.   return 0;  
  34. }  
#include <iostream>
using namespace std;

class A
{
  int i;
public:
  A(int);
};

A::A(int arg)
{
  i = arg;
  cout << "A's Constructor called: Value of i: " << i << endl;
}

// class B contains an object of A
class B
{
  A a;
public:
  B(int);
};

 B :: b (int x): a (x) // must use the initial list
{
  cout << "B's Constructor called";
}

int main()
{
  B obj(10);
  return 0;
}


Output:
A’s Constructor called: Value of i: 10
B’s Constructor called

If class A has both default construct functions, the parameter constructor is used, when the default constructor is used to initialize 'A', then b does not necessarily need to use the initialization list; If you want to initialize 'a' with the constructor of the parameter, B must use the initial list.


4) Initialization of base class data member: 
Similar to Article 3 above, if the constructor is used to initialize the group, the subclass must use the initial list.
  1. #include <iostream>  
  2.   
  3. class A  
  4. {  
  5.   int i;  
  6. public:  
  7.   A(int);  
  8. };  
  9.   
  10. A::A(int arg)  
  11. {  
  12.   i = arg;  
  13.   std::cout << ”A’s Constructor called: Value of i: ” << i << std::endl;  
  14. }  
  15.   
  16. // Class B inherits from Class A  
  17. class B : A  
  18. {  
  19. public:  
  20.   B(int);  
  21. };  
  22.   
  23. B::B(int x) :  A(x)  
  24. / / Must use initialization list  
  25.   std::cout << ”B’s Constructor called”;  
  26. }  
  27.   
  28. int main()  
  29. {  
  30.   B obj(10);  
  31.   return 0;  
  32. }  
#include <iostream>

class A
{
  int i;
public:
  A(int);
};

A::A(int arg)
{
  i = arg;
  std::cout << "A's Constructor called: Value of i: " << i << std::endl;
}

 // Class B inherits from Class A
class B : A
{
public:
  B(int);
};

B::B(int x) :  A(x)
 {// must use initialization list
  std::cout << "B's Constructor called";
}

int main()
{
  B obj(10);
  return 0;
}
operation result:
A’s Constructor called: Value of i: 10
B’s Constructor called

5) When the parameter name of the constructor is the same as the name of the data member:
If the parameters of the constructor are the same as the name of the data member, the data member must use the initialization list, or the way with this pointer is initialized.
Refer to the parameter 'I' and data members 'I' in the program below.
  1. #include <iostream>  
  2.   
  3. class A  
  4. {  
  5.   int i;  
  6. public:  
  7.   A(int);  
  8.   int getI() const  
  9.   {  
  10.     return i;  
  11.   }  
  12. };  
  13.   
  14. A::A(int i) :  i(i)  / / Or use the initial list, or use the THIS pointer  
  15. {  
  16. }  
  17.   
  18. / * You can also write the following code 
  19.  A::A(int i) { 
  20.  this->i = i; 
  21.  } 
  22.  */  
  23.   
  24. int main()  
  25. {  
  26.   A a(10);  
  27.   std::cout << a.getI();  
  28.   return 0;  
  29. }  
#include <iostream>

class A
{
  int i;
public:
  A(int);
  int getI() const
  {
    return i;
  }
};

 A :: A (INT I): i (i) // or uses a list of initialization, or uses the THIS pointer
{
}

 / * You can also write the following code
 A::A(int i) {
 this->i = i;
 }
 */

int main()
{
  A a(10);
  std::cout << a.getI();
  return 0;
}
Output:
10

6) Performance reasons:
Use the performance of the initialization list better. See the example below:
  1. #include <iostream>  
  2. class Type  
  3. {  
  4. public:  
  5.   Type()  
  6.   {  
  7.     std::cout << ”constructor called\n”;  
  8.   }  
  9.   ~Type()  
  10.   {  
  11.     std::cout << ”destructor called\n”;  
  12.   }  
  13.   Type(const Type & type)  
  14.   {  
  15.     std::cout << ”copy constructor called\n”;  
  16.   }  
  17.   Type& operator=(const Type & type)  
  18.   {  
  19.     std::cout << ”operator= called\n”;  
  20.     return *this;  
  21.   }  
  22. };  
  23.   
  24. // Do not use the initialization list  
  25. class MyClass  
  26. {  
  27.   Type variable;  
  28. public:  
  29.   MyClass(Type a) / / Suppose Type is a class defining a copy constructor and assignment operator  
  30.   {  
  31.     variable = a;  
  32.   }  
  33. };  
  34.   
  35. int main()  
  36. {  
  37.   Type type;  
  38.   MyClass mc(type);  
  39.   return 0;  
  40. }  
#include <iostream>
class Type
{
public:
  Type()
  {
    std::cout << "constructor called\n";
  }
  ~Type()
  {
    std::cout << "destructor called\n";
  }
  Type(const Type & type)
  {
    std::cout << "copy constructor called\n";
  }
  Type& operator=(const Type & type)
  {
    std::cout << "operator= called\n";
    return *this;
  }
};

 // Do not use the initialization list
class MyClass
{
  Type variable;
public:
     MyClass (Type A) // Assume Type is a class defining a copy constructor and assignment operator
  {
    variable = a;
  }
};

int main()
{
  Type type;
  MyClass mc(type);
  return 0;
}
Output:
"type type" in constructor caled // main
Copy Constructor Called // Use the newly created object Type to create parameter A in the MyClass constructor
Constructor Called // MyClass's Member Objects of Variable
Operator = "variable = a" in the Called // MyClass constructor
Destructor Called // a Lifecycle ends Destructor Called // MC Destructure, which is also destructed in Variable
Destructor Called // Type life cycle end

From the above, it is known that the compiler will follow the order below to create a MyClass object:
1. Call the Type's copy constructor to create 'a'.
2. Call the Type constructor to create member objects Variable.
3. Call Type's assignment operator and modify the member object Variable.
        variable = a; 
4. Call the destructor of Type because A is ended.

If the MYCLASS constructor is used by the initialization list, as shown in the following example:
  1. // use initialization list  
  2. class MyClass {  
  3.     Type variable;  
  4. public:  
  5.     MyClass(Type a):variable(a) {   / / Suppose Type is a class defining a copy constructor and assignment operator  
  6.     }  
  7. };  
// use initialization list
class MyClass {
    Type variable;
public:
         Myclass (Type A): variable (a) {// Assume Type is a class defining a copy constructor and assignment operator
    }
};
The output is:
constructor called
copy constructor called
copy constructor called
destructor called
destructor called
destructor called

After using the initial list, the compiler will follow the order of the following:
1. Call the copy constructor of Type to initialize 'A'.
2. Call the copy constructor of Type, and use the parameter 'a' in the initialization list to perform "variable" for member objects "Variable"initialization.
3. Call Type's destructor because A declaration period is over.

As can be seen from the above comparison example, using a list of initializations takes a step. That is, if you assign a value in the constructor, you need a COPY CONSTRUCTOR + CONSTRUCTOR + Assignment Operator + Destructor. If you use the initialization list, you only need Copy Constructor + Copy Constructor + Destructor, less A process of calling an assignment operator.

In a real application, if there are many member data, the multi-out copy process will consume a considerable performance.

Intelligent Recommendation

Why need to use C ++ constructor initialization list

Summary Use configuration initialization list function, primarily because of two aspects: Higher underlying efficiency. A comparative process, since fewer assignment step, a higher efficiency of the i...

When do you need a distributed lock?

such as: High concurrency competes for shared resources. For example, spikes need to use distributed locks for shared resources such as inventory. If you do not use distributed locks, it is likely to ...

Java - When do you need AtomicReference?

Q: Since the assignment operation referenced in java is itself atomic, why do you need AtomicReference? A: If you only need to change a reference by an assignment, you don't really need an AtomicRefer...

When do you need to implement the IDisposeable interface?

1 Introduction Students who know a little about .NET / C # should know the existence of the IDispose pattern, but they do not know how many students can understand this pattern thoroughly. The landlor...

When do you need deep copy?

operation result: in conclusion: 1. What are deep copy and shallow copy, and when do you need deep copy? Deep copy: When the data member of the copied object is a pointer type, the pointer member itse...

More Recommendation

When do you need @RequestBody annotation?

About @RequestBody When do you need to use?@RequestBody? The value from the current end is not a complete object, just when the part of the parameters are included in the REQ, no need@RequestBody When...

When do you need to rebuild an index?

When do you need to rebuild an index? Indexing can bring boosts to the database in general, but the additional overhead of the index is also not hierarchically, and the reconstruction of the index is ...

When someone asks you your name, do you need to use my name X?

When the Chinese first met, they generally liked to ask: "Your surname?" The other party generally replied: "Free of surnames." Is there a noble name for the surname? Indeed, in th...

Why do you need to initialize the list

     General constructor can be assigned to a data member, why you need to initialize the list As an example can be evidence to the contrary, some data members and the assignment can not be initi...

Initialization of static variables, do you really need lazy?

See [url=http://www.cnblogs.com/JeffreyZhao] Lao Zhao [/ url] a few days premise to [url=http://www.cnblogs.com/JeffreyZhao /archive/2009/09/02/double-check-failure.html]double-check[/url], mentioned ...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top