I guess my question should be silly but it is true that I have never seen a function pointer that is declared as virtual. Is there a reason for this?
Edit:
I should have said: Is it possible that the function it points to is specified as virtual?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, yes (and no).
Ordinary function pointers cannot point to non-static member functions. They can only point to standalone functions, which is why for ordinary function pointers the matter of function virtuality does not even come into the picture.
In order to point to member functions in C++ you need a pointer of special kind: one that has pointer-to-member-function type. A pointer of this type can point to non-virtual member functions as well and to virtual member functions. There are no special steps to take if you want to point to virtual member function. For example
However, when you make such pointer to point to a virtual member function, you have to keep in mind that it is does not really get tied to a specific version of that function in the class hierarchy. The decision about the specific function to call is made at the point of the call. For example
In the above example we made out pointer
pfooto point toB::foo. Or did we? In reality the pointer is not hard-linked toB::foospecifically. These two callswill call two different functions. The first one will call
B::foofor objectb, while the second one will callD::foofor objectd, even though we used the same pointer value in both cases. This makes sense actually in many applications.Yet, in some low-level situation it would be useful to have a pointer that is hard-tied to a specific version of virtual function. I.e. it would be nice to have a pointer that would call
B::fooforBsubobject of objectdwhen we doTo achieve that we need to be able to specify whether we want to bind it early (at the point of initialization) or late (at the point of the call). Unfortunately, C++ language provides no such functionality.