Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warn about class member self-initialization

Have a look at this piece of C++ code:

class Foo
{
    int a;

    public: Foo(int b): a(a) {}
};

Obviously, the developer meant to initialize a with b rather than a itself, and this is a pretty hard to spot error.

Clang++ will warn about this possible mistake while GCC won't, even with additional warnings enabled:

$ clang++ -c init.cpp 
init.cpp:5:27: warning: field is uninitialized when used here [-Wuninitialized]
    public: Foo(int b): a(a) {}
                        ^

$ g++ -Wall -Wuninitialized -Winit-self -c init.cpp 
$

Is there any chance of enabling the same output for g++?

like image 292
Fabian Knorr Avatar asked Aug 19 '12 11:08

Fabian Knorr


People also ask

How do you initialize a class member?

To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.

Why is initializing a class member variable during declaration not permitted?

The main reason is that initialization applies to an object, or an instance, and in the declaration in the class there is no object or instance; you don't have that until you start constructing.

Should all member variables be initialized in __ init __?

If the value is not arbitrary and simply a default value that can be changed you should be using a default value in the __init__ method that can be overridden. It can also actually be a valid initial state, which is also not arbitrary and you should set it in the __init__ method.

Can we initialize data members in a class?

In C++, class variables are initialized in the same order as they appear in the class declaration. Consider the below code. The program prints correct value of x, but some garbage value for y, because y is initialized before x as it appears before in the class declaration.


1 Answers

Use a newer gcc :-) Seems to work fine for me:

stieber@gatekeeper:~$ g++ -Wall -Wuninitialized -Winit-self -c Test.cpp
Test.cpp: In constructor ‘Foo::Foo(int)’:
Test.cpp:5:9: warning: ‘Foo::a’ is initialized with itself [-Wuninitialized]

stieber@gatekeeper:~$ gcc --version
gcc (Debian 4.7.1-2) 4.7.1
like image 185
Christian Stieber Avatar answered Sep 21 '22 16:09

Christian Stieber