Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, is it allowed to cast a function pointer to one that gets as a parameter a pointer to a base or derived class?

Will the following work as expected?:

struct A {};

struct B: public A {
    int x;
    };

void f( B* o ) {
    std::cout << o->x << std::endl;
    }

int main () {
    B b;
    b.x = 5;
    reinterpret_cast<void(*)(A*)>(f)( &b );
    }
like image 230
Yaron Cohen-Tal Avatar asked Dec 19 '22 16:12

Yaron Cohen-Tal


1 Answers

Its undefined behaviour to use such pointer after cast:

Any pointer to function can be converted to a pointer to a different function type. Calling the function through a pointer to a different function type is undefined, but converting such pointer back to pointer to the original function type yields the pointer to the original function.

From http://en.cppreference.com/w/cpp/language

So the answer to your question is actually positive - you are allowed to cast but nothing more.

You might ask "what is the point of only casting?" - this is usefull when you want to store various functions in single collection.

like image 105
marcinj Avatar answered Dec 24 '22 03:12

marcinj