Chapter 17. Constructor Failures, Part 1: Object Lifetimes

Difficulty: 4

What exactly happens when a constructor emits an exception? What if the exception comes from an attempt to construct a subobject or member object?

  1. Consider the following class:

    // Example 17-1
    //
    class C : private A
    {
      B b_;
    };
    

    In the C constructor, how can you catch an exception thrown from the constructor of a base subobject (such as A) or a member object (such as b_)?

  2. Consider the following code:

    // Example 17-2
    //
    {
      Parrot p;
    }
    

When does the object's lifetime begin? When does it end? Outside the object's lifetime, what is the status of the object? Finally, what would it mean if the constructor threw an exception?

Solution

Function try blocks were added to C++ to slightly enlarge ...

Get More Exceptional C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.