title: Catch derived exception when returning reference of base class type?
body: <p>I'm writing a windows application in C++ and encountered the following problem when working with exceptions.</p>
  
  <p>I have a base exception class from which all other exceptions derive from. In the base class I have a method for the error message of any exception. That method then returns the exception (through '*this').</p>
  
  <p>Now, the problem occurs when I want to extend a derived exception and later user it in a catch block. Since the extend method is declared in the base class, the catch block catches the base class instead of the derived class. Is there any way of working around this so that the correct derived class is caught instead?</p>
  
  <p>Here are some code illustrating the problem:</p>
  
  <pre>
  <code>
  // DECLARATIONS
  
  class BaseException {
      BaseException() { }
  
      Exception& extend( string message ) {
          // extend message
  
          return *this;
      }
  }
  
  class DerivedException : public BaseException {
      DerivedException() : Exception() { }
  }
  
  
  
  // RUNNING CODE
  
  int main() {
      try {
           ...
  
           try {
               ...
  
               // Something goes wrong
               throw DerivedException( "message1" );
           }
           catch ( DerivedException& exc ) {
               throw exc.extend( "message2" );
           }
      }
      catch ( DerivedException& ) {
          // Here is where I *want* to land
      }
      }
      catch ( BaseException& ) {
          // Here is where I *do* land
      }
  }
  </code>
  </pre>
  
  <p>At the moment I have "solved" it by <em>not</em> making the extend method virtual, but declaring it in each exception with correct return type. It works, but it's not pretty.</p>