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

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,690
Latest member
MacGyver

Latest Threads

Top