1

I following program, While creating an obj, default constructor gets called but two times copy constructor and two destructor gets called. I am not able to understand why this is happening ?

#include <iostream>
#include <exception>
using namespace std;

class sam
{
public :
    sam()
    { 
        cout<<"\n Default Constuctor"; 
    }
    sam(int a)
    {
        cout<<"\n Parameterised Constuctor";
    }
    sam(const sam &obj)
    {
        cout<<"\n Copy Constuctor";
    }

    sam & operator = (const sam &obj)
    {
        cout<<"\n Overloaded assignment operator";
    }

    ~sam()
    {
        cout<<"\n destructor";
    }
};


void fun()
{
    try
    {
        sam obj;
        throw obj;
    }
    catch(char *ptr)
    {
        cout<<"\n Catch block";
    }
    catch(sam ex)
    {
        cout<<"\n fun ";
    }
}

int main()
{

    fun();
    cout<<endl;
    return 0;
}

Output is :

enter image description here

Jodocus
  • 7,493
  • 1
  • 29
  • 45
  • Possible duplicate of [Exception and Copy Constructor : C++](https://stackoverflow.com/questions/16432959/exception-and-copy-constructor-c) – 273K May 27 '18 at 15:04

1 Answers1

1

You are throwing obj and catching it by value as ex. Copies happen when you do that and those temporary objects get destroyed as well.

General rule of thumb regarding catching exceptions; always catch by const reference (const& foo) unless you have a special reason not to do so.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70