Home > Net >  Self static referential class
Self static referential class

Time:09-17

I have been given a task of compiling the C legacy code on a new platform. In the process of compiling, I came across the following code...

class GLOBALS
{
public:
    static GLOBALS _global;
};
GLOBALS GLOBALS::_global;

class DEF
{
public:
    GLOBALS::GLOBALS _global;
};

When I am trying to compile this code, I am getting following error...

error: ‘GLOBALS::GLOBALS’ names the constructor, not the type
GLOBALS::GLOBALS _global;

I am not getting what this code is trying to achieve here.. Can anyone enlighten me on this? And how they were able to compile the code previously?

CodePudding user response:

It seems like this code tries to just have a reference to itself. The GLOBALS::GLOBALS doesn't make any sense unless the class was hidden behind another extra namesspace GLOBALS. It might just be a bug in this legacy code.

class GLOBALS
{
public:
    static GLOBALS _global;
    int dummy = 0;
};
GLOBALS GLOBALS::_global;

class DEF
{
public:
    GLOBALS _global;
};
int main()
{
  DEF x;
  x._global._global._global._global._global._global.dummy = 1;
}

The line GLOBALS GLOBALS::_global; establishes a base case. So now we can access a dummy variable inside the _global._global._global... GLOBALS object.

CodePudding user response:

Looks like this has to do with the notion of injected class name

As far as the class name within the class itself is publicly available, we are able to write something like this

std::vector<int>::vector a;

Which deduces to std::vector<int>, as far as you can write vector inside the vector class.

class Test
{
public:
    Test something;
.....
.....
   typedef some_type Type;
.....
};

When we write Test::Type, we know we are referring to some_type, and when we write Test::Test, the fact that typename Test is publicly available inside the class Test deduces it to just Test. We can write as many as we want


template<class T, class U>
struct is_same
{
    static const bool value=false;
};

template<class T>
struct is_same<T,T>
{
   
    static const bool value=true;
};


int main(){
static_assert(is_same<Test::Test::Test::Test, Test>::value);
}

And this is very weird that this compiles in gcc 4.4.7;

  • Related