http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51563
Bug #: 51563 Summary: dynamic_cast bug Classification: Unclassified Product: gcc Version: 4.6.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ AssignedTo: unassig...@gcc.gnu.org ReportedBy: gaussz...@gmail.com The following code snippet: ---------------- #include <iostream> using namespace std; struct D1{ virtual void fooD1(){} }; struct D2{ virtual void fooD2(){} }; struct C1: virtual D1{ virtual void fooC1(){} }; struct C2: virtual D1{ virtual void fooC2(){} }; struct C3: virtual D2{ virtual void fooC3(){} }; struct C4: virtual D2{ virtual void fooC4(){} }; // A-pub->C1-vir->D1 // A-pri->C2-vir->D1 // A-pub->C3-vir->D2 // A-pri->C4-vir->D2 struct A: C1, private C2, C3, private C4{ virtual void fooA(){} }; int main(int argc, char** argv){ A* pa = new A; D1* pd1 = dynamic_cast<D1*>(pa); if(pd1) cout << "success 1\n"; else cout << "FAIL 1\n"; D2* pd2 = dynamic_cast<D2*>(pd1); if(pd2) cout << "success 2\n"; else cout << "FAIL 2\n"; pd2 = dynamic_cast<D2*>(pa); if(pd2) cout << "success 3\n"; else cout << "FAIL 3\n"; pd1 = dynamic_cast<D1*>(pd2); if(pd1) cout << "success 4\n"; else cout << "FAIL 4\n"; return 0; } ------------- Compile it and run: $ g++ test.cpp -o test $ ./test success 1 success 2 success 3 FAIL 4 This is, I believe, a bug. VC++ (on windows) results in: success 1 success 2 success 3 success 4 which I think is correct. The gcc I used is: $ gcc -v Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=/usr/lib/gcc/i686-linux-gnu/4.6.1/lto-wrapper Target: i686-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.6.1-9ubuntu3' --with-bugurl=file:///usr/share/doc/gcc-4.6/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++,go --prefix=/usr --program-suffix=-4.6 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.6 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-plugin --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu --target=i686-linux-gnu Thread model: posix gcc version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3) The operating system is Ubuntu 11.10 (server 64bit). I have also tested this code snippet on Debian-6.0 with GCC-4.4.5 and CentOS-5.4 with GCC-4.1.2, which produces same result.