In C++, function pointer types are not part of any inheritance hierarchy, so the notion of downcasting doesn't directly apply. However, you can cast between function pointer types as long as the signatures are compatible.
Here's an example:
#include <iostream>
class Base {
public:
virtual void f() { std::cout << "Base\n"; }
};
class Derived : public Base {
public:
void f() override { std::cout << "Derived\n"; }
};
int main() {
void (Base::*bp)() = &Base::f;
void (Derived::*dp)() =
static_cast<void (Derived::*)()>(bp);
Derived d;
(d.*dp)();
}
Derived
Here, bp
is a pointer to the Base
version of f
, and we cast it to a pointer to the Derived
version, storing the result in dp
. This is allowed because the function signatures are the same.
However, this is generally unsafe and can lead to undefined behavior if the function pointed to by bp
is not actually a Derived
function. The cast bypasses the type system and there's no runtime check.
It's much safer to use virtual functions and let the language handle the dispatch:
Base* p = new Derived;
p->f();
Derived
In this case, the correct version of f
will be called polymorphically through the base pointer.
So while you can cast function pointers, it's often a sign of bad design and should be avoided in favor of virtual functions or other safe polymorphism techniques.
Answers to questions are automatically generated and may not have been reviewed.
Learn about first-class functions in C++: a feature that lets you store functions in variables, pass them to other functions, and return them, opening up new design possibilities