A better error message for an invalid use of dynamic_cast

Ian Lance Taylor ian@airs.com
Thu Jun 24 13:14:00 GMT 1999


In the current CVS sources, when I compile this C++ code:

class c1
{
};

class c2 : public c1
{
};

c2 *
fn (c1 *p1)
{
  return dynamic_cast<c2 *> (p1);
}

I get this error message:

/home/ian/foo1.cc: In function `class c2 * fn(class c1 *)':
/home/ian/foo1.cc:12: cannot dynamic_cast `p1' (of type `class c1 *') to type `class c2 *'

This is not especially informative, and it took me a while to realize
that the problem could be solved by adding a virtual function to class
c1.

I propose the appended patch.  This changes the error message to the
following:

/home/ian/foo1.cc: In function `class c2 * fn(c1 *)':
/home/ian/foo1.cc:12: dynamic_cast of non-polymorphic type `class c1 *'

Ian


1999-06-24  Ian Lance Taylor  <ian@zembu.com>

	* rtti.c (build_dynamic_cast_1): Give a better error message for
	an attempt to dynamic_cast a polymorphic type.


Index: rtti.c
===================================================================
RCS file: /cvs/egcs/egcs/gcc/cp/rtti.c,v
retrieving revision 1.32
diff -u -p -r1.32 rtti.c
--- rtti.c	1999/04/27 09:41:31	1.32
+++ rtti.c	1999/06/24 20:13:34
@@ -693,6 +693,9 @@ build_dynamic_cast_1 (type, expr)
 	}
     }
 
+  cp_error ("dynamic_cast of non-polymorphic type `%#T'", exprtype);
+  return error_mark_node;
+
  fail:
   cp_error ("cannot dynamic_cast `%E' (of type `%#T') to type `%#T'",
 	    expr, exprtype, type);


More information about the Gcc-patches mailing list