Class construction with initial values

后端 未结 8 1883
别那么骄傲
别那么骄傲 2020-12-06 20:05

I\'m new to C++, and the whole idea of classes - I\'m still reading a book to try and learn. The book I\'m reading says that when I construct a class, I can assign default v

8条回答
  •  無奈伤痛
    2020-12-06 20:30

    There is a subtle, but important difference between those two options. What you have at the top is called a member initialization list. When the object is created, the members in this list are initialized to whatever you put in the parenthesis.

    When you do assignment in the constructor body, the values are being first initialized, and then assigned. I'll post a short example below.

    Example 1: Member initialization

    class foo 
    {
    public:
       foo(char c, int i);
    
    private:
       char exampleChar;
       int exampleInt;
       Bar exampleBar;
    };
    
    foo::foo(char c, int i):
        exampleChar(c),
        exampleInt(i),
        exampleBar()     //Here, a bar is being default constructed
    {
    }
    

    Example 2: Constructor Assignment

    class foo 
    {
    public:
       foo(char c, int i, Bar b);
    
    private:
       char exampleChar;
       int exampleInt;
       Bar exampleBar;
    };
    
    foo::foo(char c, int i, Bar b):
        //exampleChar(c),
        //exampleInt(i),
        //exampleBar()  
    {
        exampleChar = c;
        exampleInt = i;
        exampleBar = someOtherBar;  //Here, a bar is being assigned
    }
    

    This is where it gets interesting. Note that exampleBar is being assigned. Behind the scenes, a Bar is actually first being default constructed, even though you did not specify that. Furthermore, if your Bar is more complicated then a simple struct, you will need to be sure to implement the assignment operator in order for you to initialize it in this way. Even furthermore, in order to initialize the Bar from another Bar from the member initialization list, you must implement the copy constructor!

    Example 3: Copy constructor used in member init

    class foo 
    {
    public:
       foo(char c, int i, Bar b);
    
    private:
       char exampleChar;
       int exampleInt;
       Bar exampleBar;
    };
    
    foo::foo(char c, int i, Bar b):
        //exampleChar(c),
        //exampleInt(i),
        exampleBar(b)     //Here, a bar is being constructed using the copy constructor of Bar
    {
        exampleChar = c;
        exampleInt = i;
    }
    

提交回复
热议问题