From mboxrd@z Thu Jan 1 00:00:00 1970 From: "Uwe F. Mayer" To: Subject: c++/2659: bad_cast exception not thrown Date: Thu, 26 Apr 2001 13:56:00 -0000 Message-id: X-SW-Source: 2001-04/msg00592.html List-Id: >Number: 2659 >Category: c++ >Synopsis: bad_cast exception not thrown >Confidential: no >Severity: serious >Priority: medium >Responsible: unassigned >State: open >Class: sw-bug >Submitter-Id: net >Arrival-Date: Thu Apr 26 13:56:01 PDT 2001 >Closed-Date: >Last-Modified: >Originator: Uwe F. Mayer >Release: 3.0 20010409 (prerelease) >Organization: tux.org >Environment: System: Linux tosca 2.2.18 #2 Thu Mar 8 13:48:25 PST 2001 i686 unknown Architecture: i686 host: i686-pc-linux-gnu build: i686-pc-linux-gnu target: i686-pc-linux-gnu configured with: ../gcc/configure --prefix=/usr/local/gcc --disable-nls >Description: g++ does not throw a bad_cast exception when a base-class pointer is dynamically cast to a derived-class pointer, which of course is illegal. It does, however, return a NULL pointer which was the old style error condition detection. >How-To-Repeat: Compile this program with "g++ bad_cast.cpp" and run it. Gives a Segmentation fault. Source code below: /********************************************************************** Filename: bad_cast.cpp Chapter: 9 Exceptions Compiler: Borland C++ Version 5.01 Summer 1998 C++ for C Programmers, Edition 3 By Ira Pohl ********************************************************************/ #include #include #include using namespace std; class A { public: virtual void foo() { cout << "in A" << endl; } }; class B: public A { public: void foo() { cout << "in B" << endl; } }; int main() { try { A a, *pa; B b, *pb; pa = &b; pb = dynamic_cast(pa); //succeeds pb -> foo(); pa = &a; pb = dynamic_cast(pa); //fails // if (pb==NULL) {bad_cast x; throw x; } // my g++ does not throw it pb -> foo(); } catch(bad_cast) { cout << "dynamic_cast failed" << endl; } } >Fix: Work around: Use the old style NULL-pointer test and throw the exception yourself. >Release-Note: >Audit-Trail: >Unformatted: