You really should try to see if your understanding of a particular concept is correct before you start complaining about how it's not useful or implemented in a useful manner.
In this case, for instance, none of your complaints about the shortcomings of function pointers are correct, and even a little searching should reveal that.
First of, there *is* type safety, as
void(*)()
and
void(*)(int)
are two different types that cannot be assigned to each other.
In other words, this will fail:
void foo();void bar(int);void(*pfn)(); // pfn is a pointer to a void function with no argsint main() { pfn = foo; // ok, types match pfn = bar; // will fail, type mismatch}
Your other specific complaint was that it won't allow you to point to member functions, which is also incorrect:
class Test {public: void Foo();};void(Test::*pfn)(); // pfn is of type pointer to Test member funcint main() { pfn = &Test::Foo; // Assign to Test::Foo Test t; (t.*pfn)(); // Call test.foo()}
As for virtual member functions vs. function pointers they serve completely different needs.
But, after all, you asked for the point of a function pointer.
Consider a generic sorting sorting function (such as std::sort), that can operate on any given type of data. How will the function know how to compare the elements its given? It could simply suppose that operator< is suitably defined, of course, but that would severely limit the usefulness of sort. Consider this, for instance:
struct CD { string title; string artist; int year_published; /* other stuff */};bool compareTitle ( CD const& cd1, CD const& cd2 ) { return cd1.title < cd2.title;}bool compareArtist ( CD const& cd1, CD const& cd2 ) { return cd1.artist < cd2.artist;}bool compareYearPublished ( CD const& cd1, CD const& cd2 ) { return cd1.year_published < cd2.year_published;}vector<CD> cdCollection;int main() { /* Assuming cdCollection is filled with CD's */ // Sort by title sort ( cdCollection.begin(), cdCollection.end(), compareTitle ); // Sort by artist sort ( cdCollection.begin(), cdCollection.end(), compareArtist ); // Sort by year sort ( cdCollection.begin(), cdCollection.end(), compareYearPublished );}
In cases like this function pointers (or functors) are invaluable, and the same results cannot be achieved elegantly in another fashion.
Hope that clears things up a little.
- Neophyte
EDIT: Tag typos
EDIT: Another typo