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
#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