[ 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;
}
Great. Just Great. I wanted to remain a lazy leech, just using the selfless
work others have done on subversion for my own personal advantage. The problem
is, as soon as I read HACKING and learn how to submit a patch and begin by
contributing something as tiny as a FAQ fix, I'll be hooked, and I'll start to
become a contributing member of society. Next, I'm afraid I'll want to tackle
a bite-sized task and help fix bugs and develop the product. (You guys are so
sneaky!!) :-)

("Sorry, Honey. Can you take care of that? I have to submit another svn
patch...")

Steve Dwire on the Subversion Development List

    -- Steve Dwire
    -- Post to svn-dev ( http://svn.haxx.se/dev/archive-2003-09/0077.shtml )

I'll burn my books.
		-- Christopher Marlowe


Powered by UNIX fortune(6)
[ Main Page ]