[lug] typeid calls in g++ 2.95.2
D. Stimits
stimits at idcomm.com
Tue Nov 7 14:45:31 MST 2000
"Scott A. Herod" wrote:
>
> Sorry to post a C++ question but it is rather specific to the egcs
> compilers.
>
> Does anyone know if typeid works correctly on the egcs compilers, or
> perhaps I am not using it correctly. In the code posted just below,
> I would expect the output to be:
>
> ------------------------------
> This is a B
> We got a P1B while a b* is P1B
> ------------------------------
>
> but I get
>
> ------------------------------
> This is a B
> We got a P1A while a b* is P1B
> ------------------------------
>
> The code is just below. Compile with "g++ filename.C".
> Thanks,
> Scott
>
> --------------------------------
> #include <typeinfo>
> #include <stream.h>
>
> class A {
> public:
> A() {};
> virtual ~A() {};
> virtual void spam() { cout << "This is an A" << endl; }
> };
>
> class B : public A {
> public:
> B() {};
> virtual ~B() {};
> virtual void spam() { cout << "This is a B" << endl; }
> };
>
> int whatis( A* a ) {
^^
Here you have specifically told it you are looking for an "A". The
argument "a" has been defined as type "A", and although it can hold a
"B" (which IS an "A"), it will always be "A". Polymorphism is working
correctly here, that it uses the method of "B", but considers it type
"A".
> a->spam();
> cout << "We got a " << typeid( a ).name()
> << " while a b* is " << typeid( B* ).name()
> << endl;
> }
>
> int main ( int argc, char *argv[] ) {
> B* b = new B;
> whatis( b );
> return 0;
> }
> -------------------------------------------
>
> _______________________________________________
> Web Page: http://lug.boulder.co.us
> Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
More information about the LUG
mailing list