Print the class name of the derived class using an inherited function

Is there a way to print the class name of a derived class with an inherited function without overriding that function in the derived class?

class A {
public:
    virtual void print() { printf("%s", __PRETTY_FUNCTION__); }
};

class B : public A {};

int main() {
    B b;

    b.print() // should yield "B::print()" but yields "A::print()"
}

      

I am asking that I can simply call A::print()

in the overridden function to print the attributes related to the parent class, but including the name of the current class.

+3


source to share


1 answer


__PRETTY_FUNCTION__

creates a compile-time string. A

doesn't know (and, critically, doesn't care) if something actually ends up coming from him or not. It just creates a function that outputs "virtual void A::print()"

.

If you want a function like this to correctly identify the name of the calling class, one option is to store the name as a query-related object associated with the base class.



class A {
public:
    virtual void print() {printf("(%s) : %s", get_name(), __PRETTY_FUNCTION__);}
    virtual const char * get_name() {return "A";}
};

class B : public A {
public:
    virtual const char * get_name() {return "B";}
};

      

In the comments, using typeid

to get a dynamic name will probably work as well, but I've never used it before typeid

, so I can't personally vouch for its effectiveness.

0


source







All Articles