• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 273
  • Last Modified:

A Query about Function Pointers

In my class 'galGeneticAlgorithm', I have the following definition for a function pointer:

bool (galGeneticAlgorithm::*generateChromosomeData)(galGenome*);

Now, I would like to write a function in a completely seperate module, and then attach the function pointer in the class to the new function that I've made elsewhere. I have defined the function thusly, and naturally (it's simple) it compiles OK;

bool tempFunction (galGenome* g) { return true; }


However, a few lines later, I try to assign the function pointer in one instance of galGeneticAlgorithm. Here is the code I am using;
test = new galGeneticAlgorithm(1000);
test->generateChromosomeData = &tempFunction;

Naturally, I get a horrid error telling me I can't do this. Here is said error;
error C2440: '=' : cannot convert from 'bool (__cdecl *)(galGenome *)' to 'bool (__thiscall galGeneticAlgorithm::* )(galGenome *)'


I understand that the function is defined as a 'standard function', and thus - isn't part of the correct class, but I don't know how to fix this. Please advise on how I can get this to be accepted, not only by Microsoft's Visual C++ .NET, but by all compilers (__thiscall is MSVC specific).
0
Telumehtar
Asked:
Telumehtar
  • 2
  • 2
1 Solution
 
rcarlanCommented:
You need to change the declaration to this:

bool (*generateChromosomeData)(galGenome*);

What you have used declares a pointer to a method of the galGeneticAlgorithm class. However, tempFunction is a global function. Thus the error message you were getting.

Radu
0
 
TelumehtarAuthor Commented:
That's fantastic - thanks.

Just out of curiousities sake - is there any way that I could define a method, so that I could make use of the 'this' variable? I don't think I'll need to in this case, but there are a couple of places I can think of where it would be 'neat'.
0
 
rcarlanCommented:
You could pass 'this' as a parameter to the global function - i.e. declare it like so:

bool tempFunction(galGenome*, galGeneticAlgorithm*);

0
 
TelumehtarAuthor Commented:
Of course - yup, that would work great.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now