- 1 year ago
MSVS C++: how to find address of pure virtual function at runtime
In MSVS C++, you cannot directly obtain the address of a pure virtual function at runtime because pure virtual functions do not have a concrete implementation. They serve as placeholders for derived classes to override.
However, you can obtain the address of the function pointer associated with a specific derived class's implementation of the pure virtual function. Here's an example that demonstrates how to do this:
cpp#include <iostream>
class Base {
public:
virtual void PureVirtual() = 0;
};
class Derived : public Base {
public:
void PureVirtual() override {
std::cout << "Derived::PureVirtual() called" << std::endl;
}
};
int main() {
Derived derived;
// Obtain the address of the function pointer
void (Derived::*funcPtr)() = &Derived::PureVirtual;
// Call the function using the function pointer
(derived.*funcPtr)();
return 0;
}
In this example, we define a base class Base
with a pure virtual function PureVirtual()
. The derived class Derived
overrides this function with its own implementation. We create an instance of Derived
and obtain the address of the PureVirtual()
function using the function pointer funcPtr
. We then call the function using the function pointer syntax (derived.*funcPtr)()
.
Please note that this approach works specifically for non-abstract derived classes that provide an implementation for the pure virtual function. It won't work for abstract classes or classes that don't override the pure virtual function.