Search code examples
c++inheritanceg++compiler-flags

G++ flag to protect against use of uninitialized inherited properties


How can I make g++ to protect me against the use of uninitialized parent properties into child constructor ?

struct A {
    A(int typ): type{typ} {}
    const int type;
};

struct B : public A {
    B(int typ): A(type) {}
};

int main() {
    B b{3};
    return 0;
}

Can you see the bug here, how tricky it is ? Here we build an instance of B with 3 as parameter we expect that the value of type into A is 3, right ? But we have done a typing mistake into B constructor, and we do not pass the content of the received parameter to A but the content of the value already in A::type. See the difference typ vs type in B constructor.

So how can I make g++ to warm me against this ? Because it shouldn't be allowed, A is not already initialized, we shouldn't be able do access A properties.


Solution

  • The flag to use is -Wuninitialized, it is already embedded with -Wextra and -Wall.

    But in my case, I use gcc-6.4 in c++14 mode. With this gcc version you have to use the flag, enable optimization and use the variable that have been initialized with an uninitialized variable. Only if all of these condition have been done, gcc will warn you about used of uninitialized variable.

    You can see this here : https://compiler-explorer.com/z/q53sYr - If I remove the -O2 flag or the last condition on b.type, gcc will not warn us.

    As the man page say (https://man7.org/linux/man-pages/man1/g++.1.html) :

    Note that there may be no warning about a variable that is used only to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are printed.