[ Main Page ]

C++ tips

typeinfoとtypeid

派生クラスを基底クラスに代入した場合、ポインタのままだとtypeidで基底クラスを返します。 typeidで派生クラスを得たい場合は、*をつけます。

#include <iostream>
#include <typeinfo>
class Base {
public:
   virtual void vvfunc() {}
};
class Derived : public Base {};
using namespace std;
int main() {
   Derived* pd = new Derived;
   Base* pb = pd;
   cout << typeid( pb ).name() << endl;   //prints "class Base *"
   cout << typeid( *pb ).name() << endl;   //prints "class Derived"
   cout << typeid( pd ).name() << endl;   //prints "class Derived *"
   cout << typeid( *pd ).name() << endl;   //prints "class Derived"
   delete pd;
}
Rule of Open-Source Programming #37:

Duplicate effort is inevitable. Live with it.

    -- Shlomi Fish
    -- "Rules of Open Source Programming"

How do you tell when a pineapple is ready
to eat? It picks up its knife and fork

	-- One of Nadav Har'El's Email Signatures.


Powered by UNIX fortune(6)
[ Main Page ]