dimanche 1 novembre 2015

A way to determine type of derived class with minimum code in c++ [duplicate]

This question already has an answer here:

I have a class (Say A) with many subclasses and 4 level inheritance. I have wrote function type in Base class to determine the type of class as below:

const string A::type() const {
    int status;
    const char *  realName;
    string name;
    const std::type_info &ti = typeid(*this);
    realName = abi::__cxa_demangle(ti.name(), 0, 0, &status);

    name= realName;
    int index =name.find_last_of(':');
    name = name.substr(index+1, name.length()-index-1);
    free((void *) realName);
    return name;
}

This is working with this code:

B tmp("temp");
    cout<<tmp.type() // Prints "B"

But not with this code:

A  tmp = B("temp");
    cout<<tmp.type() // Prints "A"

I have a vector<A> which can take any subclass. Is there a way to force A to return back the type of the derived class?

Aucun commentaire:

Enregistrer un commentaire