Andrew
Andrew

Reputation: 3663

Pointing to base, converted to Derived Pointer

Is it possible to get a base's derived class's type name by using typeid( TYPE ).name() ?


Example of pushing a base pointer back into a derived pointer, statically.

#include <iostream>
#include <typeinfo>
class base 
{
public:
    virtual void known() = 0;
};

class derived: public base
{
public:
    void known() { std::cout << " I guess this means "; }
    void unknown(){ known(); std::cout << " its possible "; }
};

int main()
{
    derived d;

    std::cout << typeid( d ).name() << std::endl;
     // Prints out being a pointer to a derived class
    base* b = &d;

    std::cout << typeid( b ).name() << std::endl;
    // Prints out being a pointer to a base class
    // But how would you use it, or in any other way, 
    //get the original derived type name
    derived * db = (derived*) b; 
    // db is casted at at compile time, the derived class is known
    db->unknown();
}

Upvotes: 1

Views: 92

Answers (1)

mpark
mpark

Reputation: 7904

Given an expression whose type is a polymorphic base class, The result of the typeid operator refers to a std::type_info object representing the type of the most derived object.

Example:

#include <iostream>
#include <typeinfo>

class Base {
  public:

  virtual ~Base() {}

};  // Base

class Derived : public Base {};

int main() {
  Derived derived;
  /* By reference. */ {
    Base &base = derived;
    std::cout << typeid(base).name() << std::endl;
  }
  /* By pointer. */ {
    Base *base = &derived;
    std::cout << typeid(*base).name() << std::endl;
    // NOTE: typeid(base).name() results in printing of the Base class' name.
  }
}

Both cases above print the Derived class' name.

References

Upvotes: 1

Related Questions