Class construction with initial values

后端 未结 8 1830
别那么骄傲
别那么骄傲 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:33

    There are things you can do like that that you couldn't otherwise.

    1. If one of the members doesn't have a default constructor. That's the only way you could initiate the member at construction. (same goes to base class)

    2. You can assign a value to a const member.

    3. You can assure a defined state for the class before the constructor function starts running.

    4. If a member is a reference it needs to be initialized in the Initialization List. Because references are immutable and can be initialized only once in the beginning (like const)

    0 讨论(0)
  • 2020-12-06 20:39
    foo::foo(char c, int i):exampleChar(c),exampleInt(i){}
    

    This construct is called a Member Initializer List in C++.

    It initializes your member exampleChar to a value c & exampleInt to i.


    What is the difference between Initializing And Assignment inside constructor? &
    What is the advantage?

    There is a difference between Initializing a member using initializer list and assigning it an value inside the constructor body.

    When you initialize fields via initializer list the constructors will be called once.

    If you use the assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.

    As you see there is an additional overhead of creation & assignment in the latter, which might be considerable for user defined classes.

    For an integer data type(for which you use it) or POD class members there is no practical overhead.

    0 讨论(0)
提交回复
热议问题