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?
In one of my old cross compilers (ppc_82xx-g++ gcc
version 2.95.4 20010319) both the casts work
thanks
ganesh
____________________________________________________________________________________
Never miss a thing. Make Yahoo your home page.
http://www.yahoo.com/r/hs