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.
Simple solution, replace type(this)
with type(*this)
.
It works, although I don't know how to explain it.