1

I have a function pointer to a member function in class. How do I initialize this function pointer since I get a warning on compilation every time. Here is the code:

//Node.h
class Node{
    bool (Node::*strategyPointer)(const unsigned int&);
    Node();
};

//Node.cpp
Node::Node(){

    //How do I initialize my pointer here?
}

thanks

3
  • 2
    How are you doing the initialisation currently, and what warnings do you get? Commented May 31, 2013 at 16:28
  • I am not doing any initialization currently. I am using them in a member function as follows: strategyPointer=&Node::peeringStrategyOpen; I get the error: Member strategyPointer was not initialized in this constructor. Commented May 31, 2013 at 16:30
  • That doesn't sound like an error in the assignment to me, please show the (minimal) complete code. Commented May 31, 2013 at 16:42

2 Answers 2

1

Firstly, you don't have any methods it could legally point to, so let's add some:

class Node{
    bool (Node::*strategyPointer)(const unsigned int&);

    bool firstStrategy(const unsigned int&)  { return true;  }
    bool secondStrategy(const unsigned int&) { return false; }

public:
    Node();
};

Now we have a valid value to initialize it with, just use:

Node::Node() : strategyPointer(&Node::firstStrategy) {}
Sign up to request clarification or add additional context in comments.

3 Comments

When I use strategyPointer(&Node::firstStrategy) {} in the constructor, it gives me a syntax error. Is that syntax right?
Yes. Show the minimal complete code (including the declaration of your firstStrategy or whatever method) and the error if you want us to help with them.
Awesome. If you think it might help anyone else in the future, you could edit your question to say what the problem was.
1

I wouldn't initialize it to a particular function, better to assign it that function when you actually need it. Rather just initialize it to null:

Node::Node() : strategyPointer(nullptr)
{
}

This also lets you easily test whether strategyPointer has been used, by if (strategyPointer!=nullptr) or just if (strategyPointer).

Lastly, doing it this way allows you the option of having Node be an (abstract) base class which does not in fact possess any member functions of the right signature.

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.