Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If an object is created locally and thrown as an exception in C++, how can a local object be valid outside it's 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 : 0

like image 645
Hemantharaju .H Avatar asked Dec 14 '22 10:12

Hemantharaju .H


1 Answers

A copy of the object is thrown.

like image 66
Jesper Juhl Avatar answered Dec 15 '22 23:12

Jesper Juhl