Confused with C ++ Exception throw statement

I'm new to C ++, so sorry to ask very stupid questions, but I'm confused with throw instructions in the C ++ exception handling mechanism.

  • In the code below, why are we calling a function with a name matching the class name?
  • Is this a constructor?
  • Does an instance create a class Except ?

I do not understand the syntax there.

 class A { public: class Except{}; void foo() { throw Except(); } }; int main() { A a; try { a.foo(); } catch(Except E)//exception handler { cout << "Catched exception" << endl; } } 
+6
source share
1 answer

Is this a constructor?

Yes.

Does an instance of the Except class create?

Yes again. Both of these statements are true.

 classname( arguments ) 

Where classname is the name of the class, builds an instance of this class, passing any optional arguments to the corresponding constructor of the class.

And, of course, constructors are class methods whose names match the names of the classes. That is why both of your questions have the same yes answer.

This creates a temporary instance of the class. Typically, classname used to declare a variable representing an instance of this class, but this syntax creates a temporary instance of the class, which is destroyed at the end of the expression (usually). If all that is needed is to pass the class instance to another function, a separate variable is not needed (throwing an exception also falls into this category).

+5
source

All Articles