Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointer to virtual function

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?

like image 581
Chris Avatar asked Jul 19 '11 22:07

Chris


People also ask

Why we use a pointer in virtual function?

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.

Do virtual functions only work with pointers?

Virtual method only works for base class pointers [duplicate] Bookmark this question.

What is a C++ virtual function?

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.

Why do we need virtual function in C++?

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.


1 Answers

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()
like image 90
Armen Tsirunyan Avatar answered Nov 03 '22 18:11

Armen Tsirunyan