Domanda

I have some code that typeid does not print the runtime object type. The code example is:

class interface
{
  public:
    virtual void hello()
      {
        cout << "Hello interface: " << typeid(interface).name() << endl;
      }

    virtual ~interface() {}
};

class t1 : public interface
{
  public:
    virtual void hello ()
      {
        cout << "Hello t1: " << typeid(t1).name() << endl;
      }
};

class t2 : public t1
{
  public:
    void hello ()
      {
        cout << "Hello t2: " << typeid(t2).name() << endl;
      }
};

......
  interface *p;
  t1 *p1;
  t2 *p2, *pt2;
  t3 *p3, *pt3;

  pt2 = new t2;
  std::cout << "type1: " << abi::__cxa_demangle(typeid(pt2).name(), 0, 0, &status) << "\n\n";

  p = pt2;
  assert(p != NULL);
  p->hello();
  std::cout << "type2: " << abi::__cxa_demangle(typeid(p).name(), 0, 0, &status) << "\n\n";

  p1 = dynamic_cast<t1 *>(p);
  assert(p1 != NULL);
  p1->hello();
  std::cout << "type3: " << abi::__cxa_demangle(typeid(p1).name(), 0, 0, &status) << "\n\n";

  p2 = dynamic_cast<t2 *>(p);
  assert(p2 != NULL);
  p2->hello();
  std::cout << "type4: " << abi::__cxa_demangle(typeid(p2).name(), 0, 0, &status) << "\n\n";

I build the program with "g++ -g -o ...". Then the output is:

type1: t2*

Hello t2: 2t2
type2: interface*

Hello t2: 2t2
type3: t1*

Hello t2: 2t2
type4: t2*

The print output seems right. But I expect type2 to be t2* too for RTTI. However, output is interface*. I expect type3 to be t2* too. Anything wrong?

È stato utile?

Soluzione

std::typeid gives you dynamic type information only if you pass it an object that has dynamic type, but pointers are not considered to have dynamic type since they do not contain any virtual methods.

So if you do std::typeid(*p) you'll get what you're looking for

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top