Joe.Z
Joe.Z

Reputation: 2745

Why variables declared in class, defined in function can be initialized?

In the following code:

#include <iostream>
class A {
public:
    void show_all(){std::cout << x1 << ", " << y1 << ", " << z1 << std::endl;}
    void show_uninit();
private:
    int x1;
    int y1;
    int z1;
};
void A::show_uninit()
{
    int i;
    int j;
    int k;
    std::cout << i << ", " << j << ", " << k << std::endl;
    return ;
}
int main()
{
    A a;
    a.show_all();
    a.show_uninit();
    return 0;
}

Which got the the following warning after compiled:

$ g++ -Wall test_construction.cpp
test_construction.cpp: In member function ‘void A::show_uninit()’:
test_construction.cpp:22:18: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
     std::cout << i << ", " << j << ", " << k << std::endl;
                  ^
test_construction.cpp:22:31: warning: ‘j’ is used uninitialized in this function [-Wuninitialized]
     std::cout << i << ", " << j << ", " << k << std::endl;
                               ^
test_construction.cpp:22:44: warning: ‘k’ is used uninitialized in this function [-Wuninitialized]
     std::cout << i << ", " << j << ", " << k << std::endl;
                                        ^

My understanding is the member a.x1, a.y1 and a.z1 should have got the same warnings that i, j and k got because object "a" was defined in function main() by stating "A a;", though it was declared in class out of any function. Thanks!

Upvotes: 1

Views: 67

Answers (1)

The compiler isn't smart enough to generate a warning in this case.

Note: The fact that the compiler doesn't produce any warnings or errors doesn't mean your code is right. A lot of people don't realise this when they start programming.

Compilers aren't even required to generate warnings for show_uninit, although many do, because it's relatively easy to detect a local variable that is never initialized. (If i, j and k were initialized sometimes, you might not get a warning)

When executed, show_all will print unpredictable values, just like show_uninit.

Upvotes: 4

Related Questions