mardi 27 août 2019

If an object is created locally and thrown as an exception in C++, how can a local object be valid outside is scope .i.e., in catch block?

Inside a try block, a function "fun()" is invoked. A local object of class "abc" is created inside "fun" and an exception is thrown. This local object is catched in "catch" block, and this has printed a proper value. As this object was created locally, shouldn't it have printed "0(default value)" as the stack unwinding would have happened when throw was called.

#include <iostream>

using namespace std;

class abc
{
    int var;
    public:
    abc():abc(0){}
    abc(int i):var(i){}
    void print()
    {
        cout << "inside abc : " << var << endl;
    }
};

void fun()
{
    cout << "inside fun()" << endl;
    abc obj(10);
    throw obj;
}

int main()
{
    try
    {
        cout << "inside try" << endl;
        fun();
    }catch(abc& ob)
    {
        ob.print();
    }
    return 0;
}

Output : inside try
inside fun()
inside abc : 10

My expectation: inside try
inside fun()
inside abc : 0enter code here

Aucun commentaire:

Enregistrer un commentaire