3

I would like to have a private static pointer to a function in my class. Basically, it would look like this:

//file.h
class X {
private:
    static int (*staticFunc)(const X&);
    ...
public:
    void f();

};


//file.cpp
void X::f()
{
    staticFunc(*this);
}

This gives me an "unresolved external symbol" error. I know that static members must be initialized in the .cpp too, I've tried this:

int (X::*staticFunc)(const X&) = NULL;

but this gives me an "initializing a function" error. It gives me an uglier error if I try to initialize it with an existing function. Without "= NULL", I get the same error.

Thanks.

2
  • Did you try staticFunc = NULL; in the .cpp file? (Note: This is me forgetting if you have to redeclare the type in the .cpp file, sorry) Commented Nov 30, 2010 at 18:16
  • Sorry, I wrote the code on the run. I corrected it now, of course I was passing a parameter to staticFunc when using it. And I was actually writing in the .cpp file "int (X::*staticFunc)(const X&)" instead of "int (*X::staticFunc)(const X&)". Thanks a lot for your answers, it was a stupid mistake. Commented Nov 30, 2010 at 18:39

3 Answers 3

4
//file.cpp  
int (*X::staticFunc)(const X&);

void X::f()  
{  
staticFunc(*this);  
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yep. Spelling it out, a static data member declaration in a class is just a declaration -- it also needs a separate definition outside of the class, in exactly 1 translation unit (source code file).
You can add an initializer = NULL or = &someFunc to the X::staticFunc definition. The name of the static member you want to initialize is X::staticFunc, so you need to qualify it that way. Without the X::, C++ thought you were creating a different declaration.
'= NULL' is redundant. This is guaranteed.
2

It's a member of X, so you need to say

int (*X::staticFunc)(const X&) = NULL;

Otherwise, you'd just create a global variable called staticFunc which is not related to that static member of X.

Comments

0

Couple problems here.

First error is that you're not passing a parameter in your attempt to use staticFunc. This should cause a compiler error that you're not reporting.

Second issue is that your syntax is wrong. TonyK got that one.

Comments

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.