Initializing private member variables of a class

后端 未结 5 1522
清歌不尽
清歌不尽 2021-01-03 00:04

I apologize in advance because some of my verbiage may not be 100% correct.

I will have a class like this:

class ClassName {
private:
    AnotherCl         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-03 00:32

    AnotherClass class2; creates another local object inside the constructor body, that gets destroyed at the end of the body. That is not how class members are initialized.

    Class members are initialized before the constructor body in the member initializer list between the constructor signature and body, starting with a :, like so:

    ClassName::ClassName() :
        class2(argumentsToPassToClass2Constructor),
        anotherMember(42) // just for example
    {
        /* constructor body, usually empty */
    }
    

    If you don't want to pass any arguments to the class2 constructor you don't have to put it in the initializer list. Then its default constructor will be called.

    If you simply want to call the default constructor on all of your class members, you can (and should) omit the constructor altogether. The implicitly generated default constructor will do just what you wanted.

提交回复
热议问题