I am having some troubles with member function pointers. How do I fix this, and why doesn't this work? The issue is inside main()... or so I am guessing!
#include <iostream>
#include <functional>
template<typename T>
using FnctPtr = void(T::*)(); // pointer to member function returning void
class Base {
public:
Base() : vtable_ptr{ &virtual_table[0] } {}
void foo() {
std::cout << "Base";
}
void x() {
std::cout << "X";
}
private:
// array of pointer to member function returning void
inline static FnctPtr<Base> virtual_table[2] = { &Base::foo, &Base::x };
public:
FnctPtr<Base>* vtable_ptr;
};
class Derived : public Base {
public:
Derived() {
vtable_ptr = reinterpret_cast<FnctPtr<Base>*>(&virtual_table[0]);
}
void foo() /* override */ {
std::cout << "Derived";
}
public:
inline static FnctPtr<Derived> virtual_table[2] = { &Derived::foo, &Base::x };
};
int main() {
Base* base = new Base();
base->vtable_ptr[0](); // Issue here
delete base;
}
Derivedin the example? You are not using it.error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘* base->Base::vtable_ptr (...)’, e.g. ‘(... ->* * base->Base::......reinterpret_caston a member pointer it behaves similar toreinterpret_caston function pointers. The only thing the result is good for is casting back to the original type. See 10) in the link above.static_castis required because the upcast may require adjustment of the pointer's value. Similar to how pointers to class objects cannot be downcast withreinterpret_castsafely.