3

In my code below, I wanted to test what would happen if I had an object, that contained another object whose constructor throws exception. But the code below does absolutely nothing. Nothing is printed on the console at all.

class A
{
    public:
        A()
        {
            cout << "in A constructor" << endl;
            throw "error creating A";
        }
        ~A()
        {
            cout << "destructing A" << endl;
        }
};

class C
{
    public:
    C()
    {
        cout <<"in C constructor" << endl;
    }
    ~C()
    {
        cout << "in C destructor " <<  endl;
    }

};

class B
{
    public:
    C c;
    A a;
    B(A a_, C c_): a(a_), c(c_){}
    B(){}
};


int main()
{
    try{
    B b(A, C);
    //B b;
    }
    catch(char const* s)
    {
        cout <<"catching" << endl;
    }
}

If in the try block, I use commented code instead, then it shows fine.

I also tried doing

B b(A(), C());

Still nothing.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Kraken
  • 23,393
  • 37
  • 102
  • 162
  • 4
    Welcome to the world of [the most vexing parse](https://en.wikipedia.org/wiki/Most_vexing_parse). Both attempts you have shown are *declaring functions*. – Some programmer dude Feb 18 '19 at 08:54

1 Answers1

5

This is a function declaration with return type B, name b, and two unnamed arguments of type A and C:

B b(A, C);

The same for

B b(A(), C());

as names can be enclosed by parentheses (to allow grouping, necessary when working with e.g. function pointers etc.), and even names that are left out can be enclosed by parentheses. You can turn it into a variable b of type B by

B b(A{}, C{});

One of the motivation for the curly braces to initialize variables was to disambiguate in such cases. Here, it obviously comes in handy.

lubgr
  • 37,368
  • 3
  • 66
  • 117