6

I want to define an exception which returns int. My code is given below. It's showing error.

class BadLengthException : public exception {
    public:
        int x;

    BadLengthException(int n){
        x =n;
    }

    virtual const int what() const throw ()  {
        return x;
    }
};

The error is:

solution.cc:12:22: error: conflicting return type specified for ‘virtual const int BadLengthException::what() const’ virtual const int what() const throw () { ^~~~ In file included from /usr/include/c++/7/exception:38:0, from /usr/include/c++/7/ios:39, from /usr/include/c++/7/ostream:38, from /usr/include/c++/7/iostream:39, from solution.cc:1: /usr/include/c++/7/bits/exception.h:69:5: error: overriding ‘virtual const char* std::exception::what() const’ what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT;

3
  • 1
    as a side note: don't use virtual to mark methods in derived classes that override base class virtual member functions, use dedicated override specifier instead. Commented Sep 6, 2018 at 8:33
  • @paler123 Naw, use virtual final override -- more keywords, more better! Commented Sep 7, 2018 at 15:34
  • this should be the exercise series on Inherited Code Commented Aug 22, 2020 at 17:48

2 Answers 2

7

exception::what() returns a const char*, you can't change that. But you can define another method to return the int, eg:

class BadLengthException : public std::length_error {
private:
    int x;
public:
    BadLengthException(int n) : std::length_error("bad length"), x(n) { }
    int getLength() const { return x; }
};

And then call it in your catch statements, eg:

catch (const BadLengthException &e) {
    int length = e.getLength();
    ...
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, it would probably make more sense to use std::length_error instead: "It reports errors that result from attempts to exceed implementation defined length limits for some object."
3

Hey I think you are doing the inherited code on hackerrank, I faced the same issue, also we can't change the other part of the code, so we have to override the what function,

For your C++ 11:

Now we have our int n, but we must convert it to char* to return it,

first convert it to a string with to_string() then make that a const shar* (aka c string) using .c_str()

Our class now becomes:

class BadLengthException : public exception{
    public:
    string str;

    BadLengthException(int n){
        str = to_string(n);
    }
    const char * what () const throw() {

        return str.c_str() ;
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.