简体   繁体   中英

Is it bad practice to initialize variables in class members?

If a variable's intended scope is truly local, it would only make sense to me to keep it that way. This is what I have always done. However I recently switched from vim to eclipse at work and eclipse is flagging my constructor if every member variable is not initialized in the constructor. For example, in the code below, it compiles just fine. g++ has no problem with it. Eclipse on the other hand tells me that 'a' should be initialized in the constructor.

Is there any reason why this warning might be relevant or is it just worth ignoring all together?

class C
{
public:
    C(){}
    ~C(){}
    void foo();
};

void C::foo()
{
    int a;
}

int main() {
    C c;
    return 0;
}

Eclipse on the other hand tells me that 'a' should be initialized in the constructor.

a cannot be initialized in the constructor because it's a local variable of the member function C::foo() . Eclipse is giving you a bogus warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM