// This program uses the Box class that was defined in Quiz 3

// For each line of the code, point out if the default constructor, copy
// constructor, op= or destructor is called

// I am printing out a line each in default constructor, copy constructor, op=
// and in destructor so that you know what happens in what order

#include 
using namespace std;

class Box {
    public:
	Box();
	~Box();
	Box(const Box & other);
	Box & operator = (const Box & other);
	int getValue() const;
	void setValue(int val);
    private:
	int *value; // pointer to heap allocated value
};

Box::Box()
{
    cout << "The default constructor is called" << endl;
    value = new int;
    *value = 0;
}

Box::~Box()
{
    cout << "The destructor is called" << endl;
    delete value;
}

Box::Box(const Box & other)
{
    cout << "The copy constructor is called" << endl;
    value = new int;
    *value = *other.value;
}

Box & Box::operator = (const Box & other)
{
    cout << "Operator = is called" << endl;
    if (&other == this)
        return *this;

    //copy value and return 
    *value = *other.value;
    return *this;
}

int Box:: getValue()
const
{
    return *value;
}

void Box:: setValue(int val)
{
    *value = val;
}



int main () 
{
    cout << "before line 1" << endl;
    Box a;
    cout << "\nbefore line 2" << endl;
    Box b = a;
    cout << "\nbefore line 3" << endl;
    b.setValue (17);
    cout << "\nbefore line 4" << endl;
    a = copyBox (b);
    cout << "\nbefore line 5" << endl;
    return 0;
}

Box copyBox (Box b1) 
{
    cout << "\nbefore line 1 inside copyBox" << endl;
    Box result;
    cout << "\nbefore line 2 inside copyBox" << endl;
    result = b1;
    cout << "\nbefore line 3 inside copyBox" << endl;
    return result;
}

/*
   The output of the above program is 

before line 1
The default constructor is called 

before line 2
The copy constructor is called

before line 3

before line 4
The copy constructor is called     (argument is copied into the formal parameter, Box b1 of the function copyBox)

before line 1 inside copyBox
The default constructor is called

before line 2 inside copyBox
Operator = is called

before line 3 inside copyBox
The copy constructor is called     (return value copied into a temp location)
The destructor is called            
The destructor is called
Operator = is called               (temp value is copied into Box a)
The destructor is called           (destructor for the temp location is called)

before line 5
The destructor is called
The destructor is called

*/