Search code examples
c++oopinheritancemethodsvirtual

C++ Virtual clone method, exception inheritance


I'm creating a virtual clone method in my class which I'm going to demonstrate in my main file. But when I try to do it I get errors.

Here's my class:

// includes

#include <string>
#include <exception>
#include <sstream>

namespace Vehicle_Renting {

   using namespace std;

    class Auto_Rent_Exception : public std::exception{
       protected:
          string error;
       public:
          Auto_Rent_Exception(){
          }

          virtual const string what() = 0;
          virtual ~Auto_Rent_Exception() throw();
          virtual Auto_Rent_Exception* clone() = 0;
    };

    class short_input : public Auto_Rent_Exception{
    public:
      short_input(const string errorMsg){
        stringstream ss;
        ss << errorMsg << ": short_input" << endl;
        error = ss.str();
      }
      virtual const string what(){
         return error;
      }
      virtual short_input* clone(){
         return new short_input(*this);
      }
    };
}

And here's how I'm using it:

cout << "Virtual Clone" << endl;
Auto_Rent_Exception* exc = new short_input("Smthing");   //Original copy
Auto_Rent_Exception* copy;
copy = exc->clone();
cout << exc->what();
cout << copy->what() << endl;
delete exc;

I get these errors which I don't know how to repair:

undefined reference to `vtable for Vehicle_Renting::Auto_Rent_Exception'
undefined reference to `Vehicle_Renting::Auto_Rent_Exception::~Auto_Rent_Exception()'
undefined reference to `vtable for Vehicle_Renting::Auto_Rent_Exception'
undefined reference to `Vehicle_Renting::Auto_Rent_Exception::~Auto_Rent_Exception()'
undefined reference to `Vehicle_Renting::Auto_Rent_Exception::~Auto_Rent_Exception()'

Link to error image


Solution

  • You actually need a destructor:

    virtual ~Auto_Rent_Exception()
    {
    }