private copy ctor for exception handling class

S

subramanian100in

Consider the following program:

#include <cstdlib>
#include <iostream>

using namespace std;

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

private:
Test(const Test &rhs);
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;
}

When I compile this program x.cpp as

g++ -std=c++98 -pedantic -Wall -Wextra x.cpp

I get the following compilation error.

x.cpp: In function `void fn1()':
x.cpp:29: error: `Test::Test(const Test&)' is private
x.cpp:36: error: within this context

In the catch clause in 'main()', I am receiving Test object only as
reference. So no copying of object is involved. But still the compiler
gives copy ctor being private. Why is the copy ctor needed here ?

Even if I write fn1() as,

void fn1()
{
throw Test();
}

I get the same error.

Kindly clarify.

Thanks
V.Subramanian
 

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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top