this code has an output which is kinda confusing me. Before enterig the scope why does it call the copy contructor before the display, and then before entering a scope why is the destructor called. Plus the overall output is confusing me, could you explain it to me: here is the output:
[code]
Switch::Switch()
Switch::Switch(const Switch& other)
Is Switch open?: 0
Switch::~Switch()
Switch::Switch()
Switch::Switch(const Switch& other)
Is Switch open?: 0
Switch::~Switch()
Switch::~Switch()
Switch::Switch(const Switch& other)
Is Switch open?: 1
Switch::~Switch()
Switch::~Switch()
Code:#include <iostream.h> class Switch { public: Switch() { cout << "Switch::Switch()" << endl; position = false; } Switch(const Switch& other) { cout << "Switch::Switch(const Switch& other)" << endl; position = other.position; } ~Switch() { cout << "Switch::~Switch()" << endl; } void turnOn() { position = true; } void turnOff() { position = false; } bool getPosition() const { return position; } private: bool position; }; void display(Switch sw) { bool result = sw.getPosition(); cout << "Is Switch open?: " << result << endl; } void main() { Switch aSwitch; display(aSwitch); { Switch* pSwitch = new Switch(); display(*pSwitch); delete pSwitch; } aSwitch.turnOn(); display(aSwitch); }



LinkBack URL
About LinkBacks


