Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor not throwing exception [duplicate]

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.

like image 250
Kraken Avatar asked Dec 30 '25 09:12

Kraken


1 Answers

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.

like image 171
lubgr Avatar answered Jan 01 '26 00:01

lubgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!