Search code examples
c++typesabstract-classtypeid

How to get the name of derived class using one of its methods in c++


I have this abstract base class, and I want it to be able to get the name of the class deriving from it, whatever class that may be. I want to hide this functionality from the user, because I'm just using it to make the name of a log file or something. I've heard of typeid but I can't get this to compile. I would also settle for being able to get the name of the object, instead of the class.

#include <typeinfo>

class Base{ 
public:
    virtual void lol() = 0;
    std::string getName(); 
};

std::string Base::getName() {
    return typeid(*this);  // this doesn't work!
}


class Derived : public Base{
    void lol() {}; 
};

int main(int argc, char **argv) {

    Derived d;
    std::cout << d.getName() << "\n";

    return 0; }

Solution

  • Call name() on the typeid as seen here: type_info::name

    return typeid(*this).name();
    

    Incidentally, this does kinda make the getName() function a little redundant.