Value from exception object

S

subramanian100in

consider the following program:

#include <cstdlib>
#include <iostream>

using namespace std;

class Test
{
public:
Test();
Test(const Test &rhs);
inline int value() const;

private:
int x;
};

Test::Test()
{
cout << "From Test default ctor" << endl;
x = 100;
}

inline int Test::value() const
{
return x;
}

Test::Test(const Test &rhs)
{
cout << "From Test copy ctor" << endl;
}

void fn1()
{
Test obj;
throw obj;
}

int main()
{
try
{
fn1();
}
catch (const Test &e)
{
cout << "Exception caught. Value = " << e.value() <<
endl;
}

return EXIT_SUCCESS;
}

I compiled this program x.cpp as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp

The following output is produced:

From Test default ctor
From Test copy ctor
Exception caught. Value = 0

Here why is the value is 0 and not 100 ?

However if I have the function fn1() as
void fn1()
{
throw Test();
}

the following output is produced.

From Test default ctor
Exception caught. Value = 100

Now the value is printed as 100 and also the copy ctor message is not
present.
Why is this difference ?

Kindly clarify.
Thanks
V.Subramanian
 
I

Ian Collins

consider the following program:
I compiled this program x.cpp as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp

The following output is produced:

From Test default ctor
From Test copy ctor
Exception caught. Value = 0

Here why is the value is 0 and not 100 ?
Because your copy construct or did not do its job.
Test::Test(const Test &rhs)
{
cout << "From Test copy ctor" << endl;
}

No copy of the value.
However if I have the function fn1() as
void fn1()
{
throw Test();
}

the following output is produced.

From Test default ctor
Exception caught. Value = 100

Now the value is printed as 100 and also the copy ctor message is not
present.
Why is this difference ?
The copy is optimised away in this case. Remember throw is by value, in
the first instance, obj was copied when it was thrown.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top