tags:

views:

261

answers:

2

Hello. I can not solve this problem for a while. I would be glad for some advice.

When I try to throw an exception (self created one in Java style)

throw Exception ();

compiler make a protest:

DataTypes/Date.cpp:24: error: no matching function for call to `Exception::Exception(Exception)' DataTypes/Date.cpp:24: error: in thrown expression

It does not work with any of the constructors I have. What is the problem? Here is header file of the Exception:

class Exception
{

public:
 Exception(void);
    explicit Exception(const char *);
    explicit Exception(const Exception &);
    Exception(const char *, const Exception &);
 virtual ~Exception();

 const char * message;
 const Exception & cause;

};

I should mention that when I leave just implicit constructor and the second one it works.

Thank you for any help.

+2  A: 

Your copy constructor is marked explicit, which means it isn't really a copy constructor. Thrown objects must be copyable.

To elaborate:

The explicit keyword means that a single-argument constructor cannot be used to implicitly convert a variable of the argument type to an object of the constructed type. You have to do it explicitly with the class name. For example, your constructor from const char* is explicit, so the compiler will never implicitly convert a const char* to a new object of type Exception, without you writing out Exception("some string here"). On the other hand, you do want the compiler to be able to implicitly make one Exception object into another Exception object (that's what a copy constructor does!), so by taking the constructor that would otherwise be the copy constructor and marking it with the explicit keyword, you have completely eliminated its ability to make copies.

Tyler McHenry
Well, it really is a copy ctor, even though it must be invoked explicitly. It's just not a very useful copy ctor. `:)` +1 Nevertheless.
sbi
You are right. Thanks. I can see it now. Originally it was not thought as a copy constructor. I wanted it for polymorphic structure of exceptions (like in Java). I have to do it differently.
Robin Hood
+2  A: 

By throw Exception(); you create a local instance of the exception class, which is then copied off the stack. Remove explicit from the copy-constructor.

Edit:

If your copy constructor doesn't do anything - just omit it. The compiler will generate one for you.

Nikolai N Fetissov
I see. I have not noticed that it is actually copy constructor. It was thought as an constructor with reference to exception which caused throw of this exception (like Java). Thanks.
Robin Hood
No, C++ exceptions are different from Java ones. No easy stack traces here.
Nikolai N Fetissov
The parens are required in C++.
Roger Pate
Oops, you are right, was thinking about new for some reason. Correcting.
Nikolai N Fetissov