As all the virtual function in C++ is stored in V-table. Overiding takes place in the case of virtual function. I want to ask there is any way by which we can call the Virtual function directly from the table and able too determined what functions V-table contains.
15 Answers. Show activity on this post. Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. All C++ implementations should call the version of the function defined at the level of the hierarchy in the current constructor and no further.
You can call a virtual function in a constructor. The Objects are constructed from the base up, “base before derived”.
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. Functions are declared with a virtual keyword in base class. The resolving of function call is done at runtime.
Well, actually you can. I don't care about portability, but in VS you can do it. Assuming that we are building 32-bit code with VS, the first 4 bytes at the objects address is the vtable address. By looking at the header files we know the order of methods in the vtable.
Example:
class Base
{
public:
virtual void printMessage()
{
std::cout << "Base::printMessage()" << std::endl;
}
};
class Derived : public Base
{
public:
void printMessage()
{
std::cout << "Derived::printMessage()" << std::endl;
}
};
int main(int argc, char* argv[])
{
Derived d;
unsigned int vtblAddress = *(unsigned int*)&d;
typedef void(*pFun)(void*);
pFun printFun = (pFun)(*(unsigned int*)(vtblAddress));
printFun(&d);
return 0;
}
P.S. I'm not going to ask why are you doing it, but here you have one option :-)
There is no guarantee by standard, that virtual functions are implemented using v-table
. So, only if you are sure, that compiler use v-table
- you can find needed offset.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With