Initializing private member variables of a class

后端 未结 5 1510
清歌不尽
清歌不尽 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:56

    What you did there is to create a new variable with the same name as you member,
    By doing this you overshadowed your member variable.
    Also, in the process your member constructor was silently called in the ClassName empty initialisation list.

    you can initiate the class in two ways:

        ClassName::ClassName(): class2() {}
    

    or:

        ClassName::ClassName() {
            this->class2 = AnotherClass();
        }
    

    The first way is better and a must some times. If you only use empty constructors for your members you won't see the difference, except in performance, because the compiler initialize the member by default in its initialisation list ( the part after the ":", if you don't do that, he does it silently for you... ) But if your member doesn't have an empty constructor, for example:

        AnotherClass:: AnotherClass(int a, int b)
    

    if you will try to use the second way on initialisation you will get a message like:

    error: constructor for 'Initiator' must explicitly initialize the member 'class2' which does not have a default constructor
    

提交回复
热议问题