Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguity in a fully qualified static member variable

In this sample code, there is two sentences showing the same static variable. The first one gives no ambiguity, but the second one does, why?

#include <iostream>

using namespace std;

struct A { static const char a = 'a'; };
struct B : public A { };
struct C : public A { };
struct G : public B, public C { };

int main()
{
    G v;

    cout << G::B::A::a << endl;
    cout << v.B::A::a << endl;
}

GCC error (according to some comments, there's no ambiguity in clang):

main.cpp:15:18: error: 'A' is an ambiguous base of 'G'
  cout << v.B::A::a << endl;

Code on coliru

like image 957
Peregring-lk Avatar asked May 25 '16 18:05

Peregring-lk


People also ask

Why is static member variable not defined inside the class?

Because static member variables are not part of the individual class objects (they are treated similarly to global variables, and get initialized when the program starts), you must explicitly define the static member outside of the class, in the global scope.

Can static member variables be private?

Static member variables It is essentially a global variable, but its name is contained inside a class scope, so it goes with the class instead of being known everywhere in the program. Such a member variable can be made private to a class, meaning that only member functions can access it.

Can classes have static member variables?

Static members of a class are not associated with the objects of the class: they are independent variables with static or thread (since C++11) storage duration or regular functions. However, if the declaration uses constexpr or inline (since C++17) specifier, the member must be declared to have complete type.


1 Answers

This is clearly a bug in GCC, as a GCC maintainer recommends you report it. However, until it's fixed, you can use a nasty workaround like this:

std::cout << static_cast<B &>(v).A::a;

The advantage is this will help disambiguate if in a (complex) scenario that there are variables with the same name in one of the base classes.

like image 176
uh oh somebody needs a pupper Avatar answered Sep 18 '22 18:09

uh oh somebody needs a pupper