C ++ class initialization

Source: Internet
Author: User

Reprinted from: http://blog.csdn.net/coder_xia/article/details/7447822

1. Constructor

1) Use constructors to ensure Initialization

For an empty class

[CPP] View plaincopy

    1. ClassEmpty {};

The compiler automatically declares four default functions: constructor, copy constructor, assign value function, and destructor (if you do not want to use the automatically generated function, you should explicitly reject it ), these generated functions are both public and inline. The constructor initializes data members. Using uninitialized values may cause unpredictable errors. Therefore, make sure thatEveryAll ConstructorsEveryInitialize a member.

 

2) Why can't constructors return values?

If there is a return value, either the compiler must know how to handle the return value, or the customerProgramExplicit calls of constructors and destructor by the operator. Is there security?

3) Why cannot constructors be virtual functions?

To put it simply, the virtual function call mechanism is a function that knows the interface but does not know its exact object type. However, to create an object, you must know the exact type of the object; when a constructor is called, one of its first tasks is to initialize its vptr to point to the vtable.

4) A question for the constructor:

 

[CPP] View plaincopy

  1. # Include <iostream>
  2. Using NamespaceSTD;
  3. ClassBase
  4. {
  5. Private:
  6. IntI;
  7. Public:
  8. Base (IntX)
  9. {
  10. I = X;
  11. }
  12. };
  13. ClassDerived:PublicBase
  14. {
  15. Private:
  16. IntI;
  17. Public:
  18. Derived (IntX,IntY)
  19. {
  20. I = X;
  21. }
  22. VoidPrint ()
  23. {
  24. Cout <I + base: I <Endl;
  25. }
  26. };
  27. IntMain ()
  28. {
  29. Derived a (2, 3 );
  30. A. Print ();
  31. Return0;
  32. }

First, it is about access permissions. Directly accessing base: I in the subclass is not allowed. You should change the parent class to protected or public (it is best to use protected)

 

Second, calculate the sum of the parent class and subclass I, but the parent class variable is not initialized through the subclass constructor. The constructor cannot be found during compilation, because the subclass calls the constructor, it will first find the parent class constructor, but there are no two parameters, so you canCall the parent class constructor in the initialization list

The final problem is the single-parameter constructor, which may cause implicit conversion. Because the single-parameter constructor is similar to the copy constructor, it is likely to undergo implicit conversion during calls, add the explain it keyword. The modified keyword is as follows (only the first two were modified in the programmer's interview guide)

 

[CPP] View plaincopy

  1. # Include <iostream>
  2. Using NamespaceSTD;
  3. ClassBase
  4. {
  5. Protected:
  6. IntI;
  7. Public:
  8. ExplicitBase (IntX)
  9. {
  10. I = X;
  11. }
  12. };
  13. ClassDerived:PublicBase
  14. {
  15. Private:
  16. IntI;
  17. Public:
  18. Derived (IntX,IntY): Base (X)
  19. {
  20. I = y;
  21. }
  22. VoidPrint ()
  23. {
  24. Cout <I + base: I <Endl;
  25. }
  26. };
  27. IntMain ()
  28. {
  29. Derived a (2, 3 );
  30. A. Print ();
  31. Return0;
  32. }

 

2. Initialization list

1) Use the initialization list to improve efficiency

Common initialization may be as follows:

 

[CPP] View plaincopy

  1. ClassStudent
  2. {
  3. Public:
  4. Student (string in_name,IntIn_age)
  5. {
  6. Name = in_name;
  7. Age = in_age;
  8. }
  9. Private:
  10. String name;
  11. IntAge;
  12. };

In the past, the author used to write this statement to achieve the expected results, but it is not the best practice, because in constructors, the name is assigned a value,Not InitializationThe string object first calls its default constructor, and then calls the value assignment constructor of the string class (which seems to be the basic_string class). For the age in the above example, because Int Is of the built-in type, the initial value is obtained when the value is assigned.

 

To initialize members rather than assign values, you can use the initialization list (member initialization List) to rewrite it as follows:

 

[CPP] View plaincopy

    1. ClassStudent
    2. {
    3. Public:
    4. Student (string in_name,IntIn_age): Name (in_name), age (in_age ){}
    5. Private:
    6. String name;
    7. IntAge;
    8. };

The results are the same as those in the previous example. However, during initialization, the string copy constructor is called, and the two constructor calls at the previous session will greatly improve the performance.

In some cases, you must use the initialization list to initialize the const object and reference object.

2) initialize the initial sequence of the list.

Consider the followingCode:

 

[CPP] View plaincopy

  1. # Include <iostream>
  2. Using NamespaceSTD;
  3. ClassBase
  4. {
  5. Public:
  6. Base (IntI): m_j (I), m_ I (m_j ){}
  7. Base (): m_j (0), m_ I (m_j ){}
  8. IntGet_ I ()Const
  9. {
  10. ReturnM_ I;
  11. }
  12. IntGet_j ()Const
  13. {
  14. ReturnM_j;
  15. }
  16. Private:
  17. IntM_ I;
  18. IntM_j;
  19. };
  20. IntMain ()
  21. {
  22. Base OBJ (98 );
  23. Cout <obj. get_ I () <Endl <obj. get_j () <Endl;
  24. Return0;
  25. }


The output is a random number and 98. Why? For the initialization list, the initialization of member variables strictly follows the Declaration Order, rather than the initialization order in the initialization list. If it is changed to the value assignment initialization, this problem will not occur. Of course, to use the initialization list, pay attention to the Declaration order, such as declaring the array size first and then declaring the array.

 

1) class initialization can improve the efficiency:

 1 # Include <iostream> 2 # Include <stdio. h> 3   Using  Namespace  STD;  4   Class  Boy {  5         Public  :  6 Boy ( String Name, Int Age): Name (name), age (AGE) //  Class initialization  7   {  8 Cout <This -> Name < Endl;  9 Cout < This -> Age < Endl;  10   }  11 ~ Boy ()  12   {  13 Cout < This -> Name <Endl < This -> Age < Endl;  14   }  15         String  Name;  16         Int  Age;  17   };  18   Class  Desk {  19   20   Public :  21 Desk ( Int  X): w (x), H (w ){}  22         Int  H;  23         Int  W;  24   };  25   Int  Main ()  26   { 27 Boy ( "  ABC  " , 22  );  28 Desk B ( 25  );  29 Cout <B. H <Endl <B. W <Endl; //  Class initialization order in the declared order  30       Return   0  ; 31   32 }

 

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.