5

The following program gives segmentation fault.

#include <iostream>
using namespace std;

class A {
public:
    static int& a;
};

int a = 42;
int& A::a = a;

int main() {
    a = 100;
    cout << A::a << endl;
    return 0;
}

While the following program doesn't (where the name of the global variable has been changed from a to b, with associated changes in the definition of the static data member and in the main function):

#include <iostream>
using namespace std;

class A {
public:
    static int& a;
};

int b = 42;
int& A::a = b;

int main() {
    b = 100;
    cout << A::a << endl;
    return 0;
}

Can anyone explain this behavior? I mean, there shouldn't be any issues because of name and even if there were, the compiler should have thrown an error.

3
  • @JaMiT, my apologies. I have added a small context. Commented Aug 29 at 17:56
  • This question is similar to: In C++, does Initializing a reference or pointer with itself cause UB?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Aug 30 at 16:15
  • @Fedor That does not look like a duplicate to me. That question is about intentionally initializing a reference with itself. In contrast, in this question it is unintentional, as evidenced by the text "associated changes in the definition of the static data member". Since changing the name of a global resulted in changing an initialization from = a to = b, the intent is that the initializer is that global, not the same thing that is being initialized. This question is more about name lookup. Commented Aug 30 at 18:31

1 Answer 1

14

Clang emits a helpful warning:

<source>:10:13: warning: reference 'a' is not yet bound to a value when used within its own initialization [-Wuninitialized]
   10 | int& A::a = a;
      |         ~   ^

Since the initializer is processed as if inside of the class scope, a finds A::a instead of the global variable. Use ::a:

int& A::a = ::a;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This does makes sense. My bad. I will update the flags for my compiler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.