Initializing in constructors, best practice?

后端 未结 7 844
囚心锁ツ
囚心锁ツ 2020-12-07 02:01

I\'ve been programming in C++ a while and I\'ve used both methods:

class Stuff {
public:
     Stuff( int nr ) : n( nr ) { }
private:
     int n;
}

7条回答
  •  既然无缘
    2020-12-07 02:29

    I generally try to do the initializer list when I can. For one thing, this makes it explicit that you are initializing code in the constructor. const memebers have to be initialized this way.

    If you just put code in the constructor's body, it is quite possible someone may decide to come along and move a big chunk of it into a non-constructor "setup" routine later.

    It can be taken overboard though. I have a coworker who likes to create classes that have 2 pages of initilizer code, no constructor code, and perhaps 2 pages for the entire rest of the class' code. I find that really tough to read.

提交回复
热议问题