Object initialization in C + +

Source: Internet
Author: User

It is always known that C + + objects are created with a series of initialization work by constructors. In the absence of a single class of inheritance, in addition to the constructor itself to produce and specify, but also related to the initialization steps, as well as the member initialization method and other details, this note mainly on these details, to understand the C + + object in the initialization process some of the basic operating rules.

constructor specifies

In general, When designing a class, we write the corresponding default constructor, copy constructor, copy assignment operator for this class, There is also a deconstructor. Even if we just write an empty class, the compiler will still declare a default constructor, copy constructor, copy assignment for it at compile time. Operator and Deconstructor, if there is a usage scenario in the code, then the compiler will create them.

Class mycppclass{}

Once we have written the default constructor for a class, the compiler does not generate default constructor for it, as is the case with several other functions. For constructor generated by the compiler by default, it initializes each data member with a certain rule. Considering the importance of member initialization, you need to be careful when writing your own constructor, copy constructor and assignment operator

#include  <iostream>using std::cout;using std::endl;class MyCppClass{public:     mycppclass () &NBSP;&NBSP;&NBSP;&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;STD:: cout << "in default constructor!"  <<std::endl;    }    mycppclass (const MyCppClass& &NBSP;RHS)     {        std::cout << "in  copy constructor! "  <<std::endl;    }    MyCppClass& operator=  ( CONST&NBSP;MYCPPCLASS&AMP;&NBSP;RHS)     {         std::cout << "in copy assignment operator!"  <<std::endl;        return *this;     }};int main () {    mycppclass testclass1;                 // default  Constructor    mycppclass testclass2 (TESTCLASS1);      //  copy constructor    testClass1 = testClass2;                // copy assignment operator     mycppclass testclass3 = testclass1;    // copy  constructor    return 0;}

Execution Result:

It is important to note that, in general, we always assume that the ' = ' operator appears to be calling copy assignment operator, which is an exception. That is, when a new object is defined, even if the ' = ' operator is used at this time, it actually invokes the Init function copy constructor, instead of calling copy assignment operator to perform the assignment operation.

Why Initialize List

An object includes two steps during initialization: first, allocate memory to hold the object, and second, execute the constructor. When the constructor is executed, if there is an initialization list, the initialization list is executed before the constructor function body is executed. So why would you introduce an initialization list?


C + + compared to C, in the program organization by the "function as the basic unit process-oriented "changes to" based on class-centric object-oriented, while the class also acts as a composite data type, and the initialization list is nothing more than the initialization of some data. With this in mind, it is also natural to speculate that the initialization list is associated with the initialization of the data type of the class.


After the initialization list is introduced, there are two ways in which the initialization of a class corresponding data member exists. The following is a comparison of the data member types of the class as built-in types, custom types, respectively.

The data member type is a built-in type class Mycppclass{public://Assignment operation for member initialization Mycppclass {counter = 0; }//Initialization list for member initialization mycppclass:counter (0) {}private:int counter;}

When the data member type of a class is a built-in type, the effect of the two initialization methods is the same. When the type of the data member is also a class, the initialization process will have a different place, such as:

The data member type is a custom type: A class Mycppclass{public://Assignment operation for member initialization mycppclass (string name) {counter = 0;    thename = name;    }//Initialize the list for member initialization mycppclass:counter (0), thename (name) {}private:int counter; String thename;}

In the constructor body, thename = name is the statement, Thename first calls the string's default constructor for initialization, and then calls copy assignment Opertor for copy assignment. For the initialization list, it is initialized directly via copy constructor. For obvious reasons, you can test it with the following code.

#include  <iostream> #include  <string>class SubClass{public:     Subclass ()     {        std::cout << "  in subclass default constructor! "  <<std::endl;    }    subclass (const SubClass& &NBSP;RHS)     {        std::cout << "  in subclass copy constructor! "  <<std::endl;    }    SubClass& operator=  ( CONST&NBSP;SUBCLASS&AMP;&NBSP;RHS) &NBSP;&NBSP;&NBSP;&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;STD ::cout << " in subclass copy assignment operator!"  <<std::endl;        return *this;     }};class BaseClass{public:    baseclass (CONST&NBSP;SUBCLASS&NBSP;&AMP;RHS)     {         counter = 0;        thebrother =  rhs;        std::cout << " in baseclass  default constructor! "  <<std::endl;    }    baseclass (const SubClass  &AMP;RHS,&NBSP;INT&NBSP;CNT): Thebrother (RHS), counter (CNT)     {         std::cout << " in baseclass default constructor!"  <<std::endl;    }    baseclass (const BaseClass& &NBSP;RHS)     {        std::cout << "  in baseclass copy constructor! "  <<std::endl;    }   &nBsp baseclass& operator=  (CONST&NBSP;BASECLASS&AMP;&NBSP;RHS)     {         std::cout << " in baseclass copy assignment  operator! "  <<std::endl;        return *this;     }private:    int counter;    SubClass theBrother;}; Int main () {    subclass subclass;    std::cout << "\nno member initialization list: "  <<std::endl;     Baseclass baseclass1 (subclass);    std::cout << "\nMember  initialization list:  " <<std::endl;    baseclass baseclass2 ( subclass, 1);     return 0;}

Execution Result:

that is, when it comes to custom type initialization, it is more efficient to use the initialization list to complete the initialization. This is also a great highlight of the initialization list. Even for built-in types, in some cases it is necessary to use an initialization list to do initialization work , such as const, references member variables. here is a note that has a very detailed description of the initialization list.

Several initialization nouns

When reading the Chinese version of accelerated C + +, always encountered "default initialization", "implicit initialization" and "numerical initialization", initially in understanding these nouns in the time of a few setbacks, Always feel why an initialization operation has created so many nouns that it takes less time to figure out the relationship between them.


In order to better understand them, first of all, the data types in C + + are simply divided. In C + +, the data type can be broadly divided into two types: the first is the built-in type, such as float, int, double, and so on, and the second is the custom type, which is the class that we use, the struct definition. When initializing these types of data, the difference is evident: for built-in types, the initialization of the display must precede the use, and for custom types, the initialization responsibility falls on the constructor.

int x = 0;  Display initialization of Xsubclass subclass; Initializes the default constructor that relies on subclass

The above noun "default initialization" describes an initialization state when the data for a built-in type or custom type is not displayed initialized, while implicit initialization describes how it is done under that state, for example, for built-in types, Implicit initialization in the default initialization state is actually undefined, whereas the implicit initialization of a custom type relies on its constructor.


As mentioned earlier, C + + does not guarantee the initialization of built-in types, but when a built-in type is a member of a class, the members of that built-in type are initialized by the compiler in certain conditions, which is called numeric initialization. The following scenarios are listed in accelerated C + +:

    1. object is used to initialize a container element

    2. Add a new element to the mapping table, and the object is the side effect of this add action

    3. Defines a container of a specific length, which is the element of the container

The test is as follows:

  #include  <iostream>  #include  <vector>  #include  <map> # include <string> using std::cout; using std::endl; using std::vector;  using std::map; using std::string; class NumbericInitTestClass {  Public:     void printcounter ()      {          cout << "counter = "  <<counter < <endl;     } private:     int counter; };  int main ()  {     NumbericInitTestClass tnc;      tnc. Printcounter ();     map<string, int> maptest;      cout <<maptest["Me"] <<endl;     vector< Numbericinittestclass> vecnumberictestclass (1);      vecnumberictestclass[0]. Printcounter ();      return 0; }

For built-in types that are not initialized, is an undefined value of 2009095316, and for 2, 3 cases are initialized to 0, and for the 1th case I have not thought of a suitable scenario.

Back to think, for some of the similar nouns in the book, to find ways to put them together is always a bit far-fetched:)

Some rules

here are a few basic rules about initialization, many of which come from "Effective C + +" :

1. Manual initialization of built-in objects, because C + + does not guarantee that they are initialized.

2. Constructors are best to use the Member initial column (member initialization list) instead of using assignment operations in the constructor body. The initial Value column lists the member variables in the same order as they are declared in class.

3. C + + does not like destructors to spit out exceptions.

4. Do not call the virtual function during constructors and destructors, because such calls never fall to derived class.

5. The copying function should ensure that all member variables within the object and all base class components are copied.

Object initialization in C + +

Related Article

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.