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