dynamic_cast problem

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I have this example program below.

#include<iostream>
#include<cstdio>
using namespace std;
class Base {
    public:
        Base() {}
        Base(int aa) {
            a = aa;
        }
        int a;
        char c;
        virtual void show() {
            cout << "a=" << a << endl;
        }
};
class Derived: public Base {
    public:
        Derived() {}
        Derived(int aa,int bb) {
            a = aa;
            b= bb;
        }
        int b;
        void show() {
            cout << "a=" << a << " b=" << b << endl;
        }
};

class Derived2: public Base {
    public:
        Derived2() {}
        Derived2(int aa,int bb) {
            a = aa;
            b= bb;
        }
        int b;
        void show() {
            cout << "a=" << a << " b=" << b << endl;
        }
};

int main(void) {
    Derived b(1,2);
    Base *a = (Base*)(&b);

    Derived *d1 = dynamic_cast<Derived*>(a);
    if(d1)
        cout << "cast1 ok\n";
    else
        cout << "cast1 failed\n";


    d1 = dynamic_cast<Derived*>((Derived2*)a);
    if(d1)
        cout << "cast2 ok\n";
    else
        cout << "cast2 failed\n";

    return 0;
}

 Can someone tell me why the cast2 fails but cast1
works? What effect does the cstyle cast have? 

I realize that there is no reason for anyone to do
that cstyle cast, but some code written like this had
been working with one of our old cross compilers
(ppc_82xx-g++ gcc version 2.95.4 20010319). 
I believe there is some pointer adjustment done when a
dynamic_cast is done, but no such thing is done with a
cstyle cast. So shouldnt both the casts work?

thanks
ganesh


      ____________________________________________________________________________________
Be a better pen pal. 
Text or chat with friends inside Yahoo! Mail. See how.  http://overview.mail.yahoo.com/

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux