class isThisBetter
{
public:
fPtr f;
}
Actually, this is worse because you have a public data member accessible (and changeable) by any function in the program. When this gets screwed up, you will have a whole lotta suspects.
There is no similarity between a function pointer and a virtual function.
A function pointer is a pointer to a function of the kind used to define the function pointer. That means the f public data member in your example won't compile because the compiler does not know what sorts of arguments and return type (if any) are required. You need to tell the compiler what to do. Below is your f defined as a pointer to a function that takes two int arguments and returns an int:
-
class isThisBetter
-
{
-
public:
-
int (*f)(int,int);
-
};
-
This means f can contain the address of any function so long as it has two int arguments and returns an int.
The virtual keyword on a member function tells the compiler that if you use a pointer or reference to a base class object
and there is a choice between calling the base class function or the derived class member function, the derived member function is to be called.
Remove the virtual keyword and the compiler is told that if there is a choice between the base class function and the derived function, use the base function.
Therefore, the virtual keyword allows derived class function to be called using a base class object pointer or reference. And this is how you do object-oriented coding in C++.
While it is true the addresses of these member functions are used in the class virtual function table, the table does not contain function pointers as defined in C++.
You use a function pointer when
you and not your object needs to make a run-time decision as to what function to call.