0

I basically have a class that takes a function pointer in its constructor, and then stores it in a variable to be used when a function is called on the class, like this:

class foo{ public: foo( void(*a)() = 0 ): func(a){} void call(){ if(func) func(); } private: void(*func)(); }; 

The problem occurs when I create an instance with a function that has been forward declared in an included header. By debugging I found out that the pointer func is sometimes null, while the function passed is valid, causing it not to be executed.

I'm using CodeBlocks with MinGW.

So like this:

function.h

void test(); 

function.cpp

#include "function.h" void test(){ std::cout << "Hello World" << std::endl;} 

main.cpp

#include "function.h" int main(){ foo a(test); a.call(); return 0;} 

One more thing: it doesn't always happen wrongly, so I think it has to do with optimisations or something like that.

Some things I left out because they shouldn't matter is that the foo instance is created with new, added to a std::vector and deleting itself at the end of the call() function. The destructor makes sure it is also erased from the std::vector. That all happens in a different cpp file that also includes function.h

SOLVED

9
  • 1
    Code seems like it should work. Please show examples of the way you construct and use foo objects. Commented Nov 7, 2014 at 21:51
  • afair functions declared in headers are inlined Commented Nov 7, 2014 at 22:06
  • Are you sure you're linking with function.cpp? Commented Nov 7, 2014 at 22:18
  • It shows in the list of files that will be compiled, so it should be linked. Commented Nov 7, 2014 at 22:23
  • 1
    The stuff you "left out because they shouldn't matter" is almost certainly the problem. Post it! Commented Nov 7, 2014 at 22:36

1 Answer 1

1

By the looks of the class, it seems that you would never want to construct "foo" with a null function pointer. Have you considered throwing an exception in the constructor if the function pointer is null? Doing so may help you determine the location within the code where "foo" is constructed using a null pointer.

Sign up to request clarification or add additional context in comments.

1 Comment

I found out that a mistake in the for-loop that creates foo-objects: it stopped 1 iteration too early. Thanks for all the replies, the problem has been solved.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.