Reputation: 2281
I have defined my own exceptions ans I get errors at compile time:
/home/me/my_proj/CMyExceptions.hpp:38:63: error: no matching function for call to ‘MyException1::MyException1()’
MyException2(const std::string& msg) : m_msg(msg) {}
^
/home/me/my_proj/CMyExceptions.hpp:38:63: note: candidates are:
/home/me/my_proj/CMyExceptions.hpp:23:3: note: MyException1::MyException1(const string&)
MyException1(const std::string& msg) : m_msg(msg) {}
^
/home/me/my_proj/CMyExceptions.hpp:23:3: note: candidate expects 1 argument, 0 provided
/home/me/my_proj/CMyExceptions.hpp:17:7: note: MyException1::MyException1(const MyException1&)
class MyException1 : public std::exception
^
My exceptions are:
class MyException1 : public std::exception
{
private:
std::string m_msg;
public:
MyException1(const std::string& msg) : m_msg(msg) {}
virtual ~MyException1() throw() {};
virtual const char* what() const throw()
{
return m_msg.c_str();
}
};
class MyException2 : public MyException1
{
private:
std::string m_msg;
public:
MyException2(const std::string& msg) : m_msg(msg) {}
virtual ~MyException2() throw() {};
virtual const char* what() const throw()
{
return m_msg.c_str();
}
};
What am I doing wrong? Shall I call the parent constructor (MyException1
) before initialization?
Upvotes: 0
Views: 50
Reputation: 21763
You have m_msg in MyException1 and put it again in MyException2. This means MyException2 actually contains two m_msg variables. Is this what you intended?
The error message is because MyException1 does not have a default constructor, so MyException2 must call its constructor in the initialization list. I suggest
class MyException2 : public MyException1
{
public:
MyException2(const std::string& msg) : MyException1(msg) {}
};
Upvotes: 3