Search code examples
c++functiondefault-value

implicit default value for class member variable?


I'm doing C++ tests for my certification exam and I came across this exercise that i don't understand: (the question is what is the output of the following program)

#include <iostream>
using namespace std;
class A {
public :
    float v;
    float set(float v) {
    A::v += 1.0;
    A::v = v+1.0;
    return v;
    }
    float get(float v){
    v +=A::v;
    return v;
    }
};

int main()
{
    A a;
    cout<< a.get(a.set(a.set(0.5)));
    return 0;
}

I expected to have an error on the first line of the set function since A::v was never initialized, but my program compiles and it seems that A::v has value 0 by default.. Could someone please explain why there is no compilation error?


Solution

  • Like you mentioned, the first line of set used A::v, which was never initialized before. However, that itself doesn't produce an error, it is undefined behavior. What it means is the compiler may initialize it for you, or it might just pickup a random number it sees on the memory, or whatever they are pleased to. The C++ standard doesn't say what needs to happen, so it left the compiler to decide whatever is easy.

    However, whatever happens on that line shouldn't matter too much in your code, in most cases. The reason is A::v will be re-assigned to v + 1 on the next line. So it should almost always print 2 at the end.