You are not logged in.
C++
Hi everyone, I am trying to implement a simple vector with the usual operations of vector sum, and product for a scalar.
If someone tries to sum up two vectors of different size, I want throwing an exception of type different_sizes that I defined:
class different_sizes : public std::exception
{
public:
explicit different_sizes(const std::string& error_message) :
what_(error_message) {}
virtual const char* what() const throw ()
{ return what_.c_str(); }
virtual ~different_sizes() throw () {}
private:
std::string what_;
};
and it works.
But I'd like being more precise about the kind of error and derivate from runtime_error or range_error. The obvious solution, changing from
class different_sizes : public std::exception
to
class different_sizes : public std::runtime_error
just does not works... the compiler says:
[...]
error: no matching function for call to 'std::runtime_error::runtime_error()'
[...]
note: candidates are: std::runtime_error::runtime_error(const std::string&)
[...]
I checked the source of the stdlib, and in fact std::exception have a constructor without arguments, while runtime_error does not.
How I can I explain the compiler he should use the const std::string the different_sizes constructor obtains?
Thanks everyone.
Offline
It's your constructor - when you extend a class, your constructor needs to call the superclass constructor. When not specified, it uses the default, ie. no arguments, constructor. If the superclass has no default constructor, you get this error.
Try this:
explicit different_sizes(const std::string& error_message) :
std::runtime_error(error_message), what_(error_message) {}
Offline
Simple and clear.
Thanks a lot Cerebral...
Offline