First Class Functions

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?

Abstract art representing computer programming

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.

This Question is from the Lesson:

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved