0

I mean to define a function in the base class that is able to print the class of the object calling it, resolving correctly if it is of any derived class.

For instance this (expectedly) fails:

//======================================================
// demangle is copied from https://stackoverflow.com/a/4541470/2707864
#include <string>
#include <typeinfo>

std::string demangle(const char* name);

template <class T>
std::string type(const T& t) {
    return demangle(typeid(t).name());
}

//======================================================
// Class definition
class level1 {
public:
    virtual void whoami() const {
        std::cout << "I am of type " << type(this) << std::endl;
    }
};

class level2 : public level1 {
};

//======================================================
// Testing

level1 l1;
l1.whoami();
level2 l2;
l2.whoami();

which produces

I am of type level1 const*
I am of type level1 const*

How can I get level2 in the second case, if possible at all?
I mean to not redefine the function in each derived class.

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • your code doesn't compile - it's missing `include `. the missing demangle code is redundant, simply use `return typeid(t).name()` it conveys the message perfectly. – OrenIshShalom May 01 '21 at 02:18

1 Answers1

1

Simple solution, replace type(this) with type(*this). It works, although I don't know how to explain it.

  • This is how `typeid` works. When being passed `this`, the static type is always `level1 const*`; when being passed `*this`, the static type is still `level1` but the dynamic type is `level2`. – songyuanyao May 01 '21 at 01:39