rugermini
rugermini

Reputation: 115

Initializing static member function pointer to function of same name

I got segfaults and could boild down the code to this; I initialize a static function pointer that is a member with a global function of the same name:

#include <iostream>

class def{
        public:
static void (*pt)();
};

void pt()
{
        std::cout << "works" << std::endl;
}

void (*def::pt)()=pt;
main(int argc,char* args[])
{
  std::cout << "pointer is " << def::pt << std::endl;
  def::pt();
}

This gives

pointer is 0
Segmentation fault (core dumped)

So the initalization seems to fail. If I now change the name of the function in the initialization to something else, say:

[...]        
void pt2()
{
        std::cout << "works" << std::endl;
}

void (*def::pt)()=pt2;
[...]

This resolves the problem. I am wondering what is going wrong there. Is that a scoping issue?

Upvotes: 3

Views: 71

Answers (1)

TartanLlama
TartanLlama

Reputation: 65600

void (*def::pt)()=pt;    

Because you are defining a static member of def, names declared in def shadow names declared without.

You can select the correct version of pt by explicitly specifying pt in the global namespace:

void (*def::pt)() = ::pt;
//                  ^^

Upvotes: 3

Related Questions