Downcasting Function Pointers in C++

Is it possible to downcast a function pointer to a more specific function pointer type in C++? For example, casting a pointer-to-base to a pointer-to-derived. If so, how is it done and what are the risks?

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.

First Class Functions

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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Returning Function Pointers from Functions
How can I return a function pointer from a function in C++? What are some use cases for doing this?
Capturing Local Variables in C++ Lambdas
How can I capture local variables from the enclosing scope when using lambdas in C++? What are the different capture modes and when should I use each?
Function Pointers and Virtual Functions
How do function pointers interact with virtual functions in C++? Can I take a pointer to a virtual function?
Understanding Complex Function Pointer Syntax
C++ function pointer syntax can get quite complex, especially with things like typedef and using directives. How can I decipher complex function pointer syntax?
Function Pointers and Static Member Functions
Can I take a function pointer to a static member function in C++? How is it different from taking a pointer to a non-static member function?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant