سؤال

Possible Duplicate:
Printing derived class name in base class

I am using GCC, and the following code output something unexpected

#include <iostream>
#include <typeinfo>
using namespace std;

class B {
  public:
  B ( B * ptr) { cout<< typeid(*ptr).name()<<endl;}
};

class  D : public B {
  public:
  D() : B(this) { cout<<typeid(this).name()<<endl;}
};

int main()
{
    D d;
    return 0;
}

output:

1B
P1D

Can anyone please explain to me why here the base class cannot tell the type of the derived class correctly? Many thanks

هل كانت مفيدة؟

المحلول

Two reasons:

  1. The object (*ptr) hasn't been fully constructed yet.
  2. Your classes are not polymorphic (no virtual member functions), so no dynamic type information exists.

نصائح أخرى

that thing really depends on compiler. msvc provides different typeid string for that.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top