private copy ctor for exception handling class

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • subramanian100in@yahoo.com, India

    private copy ctor for exception handling class

    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(cons t 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(con st 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
Working...