[ 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;
}
*Linus Torvalds:* "95% of Programmers consider themselves in the top 5%".

*Shlomi Fish's Corollary:* "95% of Programmers consider 95% of the code they
did not write, in the bottom 5%."

    -- Shlomi Fish
    -- Shlomi Fish's Aphorisms Collection ( http://www.shlomifish.org/humour.html )

Chuck Norris read the entire English Wikipedia in 24 hours. Twice.

( Actually, he wrote it in 24 hours. Twice. (The first time longhand in blood.
The second time he typed it in from memory (by *Drew Roberts*). )

    -- Shlomi Fish
    -- Chuck 
                      Norris Facts by Shlomi Fish ( http://www.shlomifish.org/humour/bits/facts/Chuck-Norris/ )


Powered by UNIX fortune(6)
[ Main Page ]