Problem 1014

Summary: Destructor in base classes are not virtual
Product: Geant4 Reporter: Giuseppe Vacanti <gvacanti>
Component: processes/opticalAssignee: gum
Status: RESOLVED FIXED    
Severity: normal CC: Gabriele.Cosmo
Priority: P5    
Version: 9.1   
Hardware: All   
OS: All   

Description Giuseppe Vacanti 2008-06-09 21:29:49 CEST
Many of the Geant4 classes are supposed to be used as base classes. In quite a few cases the base classes do not have a virtual destructor. In general one runs the risk that memory will be sliced, and the base class destructor will never be called (see http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7), but I tend to ignore that problem with Geant4, because one never deletes pointers in Geant4, and when the system does the application is shutting down.

This is however a general problem that should be addressed, because it hinders a number of perfectly legal c++ constructs. In particular, if the base class has no virtual functions, it is impossible to use dynamic_cast to cast a pointer to the base class to a derived class, and one is forced to use an unsafe cast, as is the case in G4OpBoundaryProcess:

if (Surface) OpticalSurface = (G4OpticalSurface*) Surface->GetSurfaceProperty();

One would probably want to do this instead:

OpticalSurface = dynamic_cast<G4OpticalSurface *>(Surface->GetSurfaceProperty())

and then check if the conversion took place.

Take now an extended version of G4OpBoundaryProcess, where I introduce two types of G4OpticalSurface (call those G4OpticalSurface1 and 2). The c-style cast now does not work because I could have more than one derived class. But if the destructor of the base class was virtual, one could do this

  if(OpticalSurface1 = dynamic_cast<G4OpticalSurface1 *>(Surface->...){
    deal with this type of surface
  else if(...2 = dynamic_...2 *>...){
    deal with this type of surface
  } else
    error

In my application I would actually like to do this, but I cannot because of the problem described here.

Thanks for your attention.
Comment 1 Gabriele Cosmo 2008-06-27 11:13:24 CEST
Thank you. Virtual destructor has been added to G4SurfaceProperty.
The fix will be available in the next release.