Search code examples
c++virtual

Can the virtual function be found at runtime without calling?


I have a base class Base, with many derived classes (eg. Derived1, Derived2). Base has a pure virtual function fn, which is called many times using a Base pointer. Every time the function is called, I need to do some extra logging and related stuff. In particular, I use BOOST_CURRENT_FUNCTION in the derived-class functions to find out which function was called. Is there a way to know this information before calling the function, so that I do not have to rewrite the bookkeeping code in every derived function?

Edit: I wish to avoid writing __PRETTY_FUNCTION__ in each derived function.

#include <iostream>
using namespace std;

class Base {
public:
virtual void fn() = 0;
};

class Derived1:public Base {
public:
void fn() {
cout<<__PRETTY_FUNCTION__<<endl;
}
};

class Derived2:public Base {
public:
void fn() {
cout<<__PRETTY_FUNCTION__<<endl;
}
};

int main()
{
    int choice =0;
    Base *ptr1 = nullptr;
    cout<<"Choose 0/1: "<<endl;
    cin>>choice;
    if(choice == 0) {    
       ptr1 = new Derived1;
    }else {
       ptr1 = new Derived2;
    }

    //********CAN I WRITE SOMETHING HERE, TO GIVE THE SAME RESULT?
    ptr1->fn();
}

Solution

  • No, it cannot be. C++ does not support this kind of introspection. __PRETTY_FUNCTION__ is all you're gonna get.