This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

c++/2659: bad_cast exception not thrown



>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 <iostream>
#include <exception>
#include <typeinfo>
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<B*>(pa);      //succeeds
      pb -> foo();
      pa = &a;
      pb = dynamic_cast<B*>(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:


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]