If you have a struct like this one
struct A {
void func();
};
and a reference like this one
A& a;
you can get a pointer to its func
method like this:
someMethod(&A::func);
Now what if that method is virtual and you don't know what it is at run-time? Why can't you get a pointer like this?
someMethod(&a.func);
Is it possible to get a pointer to that method?
If a class has one or more member functions that are virtual, then the compiler creates what is called a virtual function table for that class. This table has a pointer (memory address) for each virtual member functions. The pointer points to the location of the correct code for that member function.
Virtual method only works for base class pointers [duplicate] Bookmark this question.
A virtual function in C++ is a base class member function that you can redefine in a derived class to achieve polymorphism. You can declare the function in the base class using the virtual keyword.
We use virtual functions to ensure that the correct function is called for an object, regardless of the reference type used to call the function. They are basically used to achieve the runtime polymorphism and are declared in the base class by using the virtual keyword before the function.
Pointers to members take into account the virtuality of the functions they point at. For example:
#include <iostream>
struct Base
{
virtual void f() { std::cout << "Base::f()" << std::endl; }
};
struct Derived:Base
{
virtual void f() { std::cout << "Derived::f()" << std::endl; }
};
void SomeMethod(Base& object, void (Base::*ptr)())
{
(object.*ptr)();
}
int main()
{
Base b;
Derived d;
Base* p = &b;
SomeMethod(*p, &Base::f); //calls Base::f()
p = &d;
SomeMethod(*p, &Base::f); //calls Derived::f()
}
Outputs:
Base::f()
Derived::f()
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