C ++ learning-constructor initialization list (4)

Source: Internet
Author: User

Author: gzshun. Original Works. Reprinted, please indicate the source!
Source: http://blog.csdn.net/gzshun


In terms of concept, constructor can be considered to be implemented in two phases:

1. Initialization phase;
2. Common computing stage. (The computing stage consists of all the statements in the constructor)
Whether or not the Members display initialization in the constructor initialization list, data members of the class type are always initialized in the initialization phase. Initialization occurs before the start of the computing phase.
Suggestion: Use the constructor to initialize the list.
Note: you must use the initialization method for any const or reference type member and any member of the class type without the default constructor.
You can use constructors to initialize the list to avoid compilation errors.
Explanation: no default constructor class? What does that mean?
In most compilers, a class is declared. If the class has no explicit declaration and constructor definition, the compiler will generate a default constructor in the compilation phase. If you declare a constructor in this class, the compiler will not generate default constructor, but will use your own constructor. To avoid compilation errors, it is best to use the constructor initialization list to initialize objects of this class.
----- Excerpt from C ++ primer Chinese Version 4th

Class member initialization includes the initialization of Class Object members and class data members. The key to Initialization is the initialization list of the constructor. In the initialization list of the constructor, the order is also required. Only constructors can have the effect of member initialization. Common member functions do not have this function, for example:

[CPP]
View plaincopy
  1. Void cinit: setxy (int x, int y): MX (x), My (y)
  2. {
  3. }

This Initialization is incorrect. setxy is not a constructor. Therefore, common member functions can only set the values of variables or objects by assigning values.

[CPP]
View plaincopy
  1. Void cinit: setxy (int x, int y)
  2. {
  3. MX = X;
  4. My = y;
  5. }

A cinit class is declared as follows:

[CPP]
View plaincopy
  1. Class cinit
  2. {
  3. Public:
  4. Cinit (int x, int y );
  5. Void show () const;
  6. PRIVATE:
  7. Int MX;
  8. Int my;
  9. };
  10. Void cinit: Show () const
  11. {
  12. Cout <"MX =" <MX <Endl
  13. <"My =" <my <Endl;
  14. }

I. Basic usage of the constructor initialization list
This is the usage of the normal initialization list
Initialization:

[CPP]
View plaincopy
  1. Cinit: cinit (int x, int y): MX (x), My (y)
  2. {
  3. }

The result is equivalent
Assignment:

[CPP]
View plaincopy
  1. Cinit: cinit (int x, int y)
  2. {
  3. MX = X;
  4. My = y;
  5. }

Ii. Sequence of member Initialization
In the constructor initialization list, the initialization order of members is the order of declared members.
Example 1: James wants to initialize MX with X and then initialize my

[CPP]
View plaincopy
  1. Cinit: cinit (int x, int y): MX (x), My (MX)
  2. {
  3. }
  4. Cinit test (2, 3 );
  5. Test. Show ();

The result is:

[Plain]
View plaincopy
  1. MX = 2
  2. My = 2

Both Mx and my are initialized successfully.


Example 2: Li Si wants to initialize my first and then use my to initialize MX

[CPP]
View plaincopy
  1. Cinit: cinit (int x, int y): My (Y), MX (my)
  2. {
  3. }
  4. Cinit test (2, 3 );
  5. Test. Show ();

The result is:

[Plain]
View plaincopy
  1. MX = 2147344384 (different machines may be inconsistent)
  2. My = 3

Obviously, MX is not initialized, and my is initialized to 3.


It can be seen from this that the constructor executes initialization actions in the declared order of variables. Therefore, in example 2, the constructor first initializes MX, but at this time my is not initialized, this is the case. In the initialization list of the constructor,It is best to initialize the class according to the declared sequence of the member variables in the class.


Iii. Under what circumstances will the constructor be used to initialize the list?
1. Const object
2. Reference Type object
Because the const object and the reference type object can only be initialized and cannot be assigned a value, they must be initialized in the initialization list.
3. Class Object (described below)

To illustrate 3. Class Object (described below), if a parent class is defined as follows:

 

[CPP]
View plaincopy
  1. Class ca {
  2. Public:
  3. CA () {cout <"using CA's constractor/N ";}
  4. CA (int K) {cout <"using CA's 2nd constractor, K is" <k <Endl; M = K ;};
  5. Virtual ~ CA () {cout <"using CA's disconstractor/N ";}
  6. Void output () {cout <"The M is" <m <Endl ;}
  7. PRIVATE:
  8. Int m;
  9. };

Note that Class A has a private member M.

Assume that a subclass is defined as follows:

[CPP]
View plaincopy
  1. Class CB: public CA {
  2. Public:
  3. CB (int K) {M = K ;}
  4. };

Obviously, it is wrong. Class B cannot directly access Class A member M.

 

This definition is also incorrect:

[C-sharp]
View plaincopy
  1. Class CB: public CA {
  2. Public:
  3. CB (int K) {_ super: Ca (INT) k );}
  4. };

In this way, a temporary variable instance of the CA class is constructed in CB (int K), and the function is no longer executed. If:

[C-sharp]
View plaincopy
  1. Cb B (2 );

The execution result is:

Using Ca's constractor
Using Ca's 2nd constractor, K is 2
Using Ca's disconstractor

Using Ca's disconstractor

This indicates that a CB instance is constructed by default by calling Ca (), and then a Ca (2) instance is declared.

 

The correct method is as follows:

[C-sharp]
View plaincopy
  1. Class CB: public CA {
  2. Public:
  3. CB (int K): Ca (k ){}
  4. };

This shows the constructor that calls the parent class in the subclass.

4. In constructor, Which of the following is more efficient for value assignment initialization and initialization list initialization? Why?
Let's look at an example and we can see that:

[CPP]
View plaincopy
  1. # Include <iostream>
  2. Using namespace STD;
  3. Class cobj
  4. {
  5. Public:
  6. Cobj ()
  7. {
  8. Cout <"Call default constructor" <Endl;
  9. }
  10. Cobj (const cobj & OBJ)
  11. {
  12. MX = obj. mx;
  13. Cout <"Call replication constructor" <Endl;
  14. }
  15. Cobj & operator = (const cobj & OBJ)
  16. {
  17. If (& OBJ! = This)
  18. {
  19. MX = obj. mx;
  20. }
  21. Cout <"Data assignment" <Endl;
  22. Return * this;
  23. }
  24. PRIVATE:
  25. Int MX;
  26. };
  27. Class cinit
  28. {
  29. Public:
  30. Cinit (const cobj & OBJ): mobj (OBJ)
  31. {
  32. // Mobj = OBJ;
  33. }
  34. PRIVATE:
  35. Cobj mobj;
  36. };
  37. Int main ()
  38. {
  39. Cobj OBJ;
  40. Cout <Endl;
  41. Cinit test (OBJ );
  42. Return 0;
  43. }

1. If the cinit constructor is:

[CPP]
View plaincopy
  1. Cinit (const cobj & OBJ): mobj (OBJ)
  2. {
  3. }

The execution result is:[Plain]
View plaincopy

  1. The output of the constructor that calls the default constructor // cobj OBJ;

  2. Call the replication Constructor

When the initialization list of the constructor cinit initializes the mobj object, the copy constructor is called once, and a total of 1 behavior is required.

2. If the cinit constructor is:

[CPP]
View plaincopy
  1. Cinit (const cobj & OBJ)
  2. {
  3. Mobj = OBJ;
  4. }

The execution result is:

[Plain]
View plaincopy
  1. The output of the constructor that calls the default constructor // cobj OBJ;
  2. Call the default constructor
  3. Data assignment

When assigning values to the mobj object in the constructor body, the default constructor is called first, and the operator = value assignment operator is called. A total of two actions are required.

So we can come to the following conclusion:For user-defined class types, it is more efficient to use the constructor initialization list for initialization than to assign values to initialization in the constructor body. For built-in types, the efficiency is similar.

5. Example of using the constructor initialization list

[CPP]
View plaincopy
  1. /* Class member initialization: Find a rectangle composed of two points */
  2. # Include <iostream>
  3. Using namespace STD;
  4. Class ccenterpoint
  5. {
  6. Public:
  7. Ccenterpoint (INT posx, int posy): mposx (posx), mposy (posy)
  8. {
  9. }
  10. Void showpos () const
  11. {
  12. Cout <"midpoint coordinates between two points: (" <mposx <"," <mposy <")" <Endl;
  13. }
  14. PRIVATE:
  15. Int mposx;
  16. Int mposy;
  17. };
  18. Class carea
  19. {
  20. Public:
  21. Carea (INT length, int width): mlength (length), mwidth (width)
  22. {
  23. }
  24. Void showarea () const
  25. {
  26. Cout <"rectangular area composed of 2 points:" <mlength * mwidth <Endl;
  27. }
  28. PRIVATE:
  29. Int mlength;
  30. Int mwidth;
  31. };
  32. Class crect
  33. {
  34. Public:
  35. Crect (INT posx1, int posy1, int posx2, int posy2)
  36. : Mpoint (posx1 + posy1)/2, (posx2 + posy2)/2 ),
  37. Marea (posX2-posX1, posY2-posY1)
  38. {
  39. }
  40. Void show () const
  41. {
  42. Mpoint. showpos ();
  43. Marea. showarea ();
  44. }
  45. PRIVATE:
  46. Ccenterpoint mpoint;
  47. Carea Marea;
  48. };
  49. Int main ()
  50. {
  51. Crect rect (10,100, 20,200 );
  52. Rect. Show ();
  53. Return 0;
  54. }

Execution result:

[Plain]
View plaincopy
  1. Midpoint coordinates between two points: (55,110)
  2. Rectangular area composed of 2 points: 1000

Happy learning!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.