You are not logged in.

#1 2006-12-09 16:11:01

ezzetabi
Member
Registered: 2006-08-27
Posts: 947

Deriving from std::runtime_error C++

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

#2 2006-12-09 18:21:29

Cerebral
Forum Fellow
From: Waterloo, ON, CA
Registered: 2005-04-08
Posts: 3,108
Website

Re: Deriving from std::runtime_error C++

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

#3 2006-12-10 11:22:27

ezzetabi
Member
Registered: 2006-08-27
Posts: 947

Re: Deriving from std::runtime_error C++

Simple and clear.
Thanks a lot Cerebral... big_smile

Offline

Board footer

Powered by FluxBB