[ 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;
}
I pretty rapidly realized that the App Architecture group knew even less than
I did about macros. At least, I had talked to a handful of macro developers
and some Excel old-timers to get a grip on what people actually did with Excel
macros: things like recalculating a spreadsheet every day, or rearranging some
data according to a certain pattern. But the App Architecture group had merely
thought about macros as an academic exercise, and they couldn't actually come
up with any examples of the kind of macros people would want to write.
Pressured, one of them came up with the idea that since Excel already had
underlining and double-underlining, perhaps someone would want to write a
macro to triple underline. Yep. REAL common. So I proceeded to ignore them as
diplomatically as possible.

    -- Joel Spolsky
    -- "Two Stories" ( http://www.joelonsoftware.com/articles/TwoStories.html )

Rule of Open-Source Programming #4:

If you don't work on your project, chances are that no one will.

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


Powered by UNIX fortune(6)
[ Main Page ]