I am trying to get familiar with constructors and destructors in C++. The below program simply creates a complex number, prints it on the stdio and exits. I have created 3 objects (1. using default constructor, 2. using explicit constructor and third using the copy constructor. Before exiting, it destructed 4 objects. Why my program below is destructing more objects than the constructor ever created?
#include <iostream>
using namespace std;
class complex
{
private: float a; float b;
public: float real(){return a;};
float imag(){return b;};
complex(){a=0.0; b=0.0;cout << "complex no. created."<<endl;};
complex(float x, float y){a=x; b=y;};
~complex(){cout << "complex no. with real part " << this->real() << " destroyed" << endl;};
void display(){cout << a << '+' << b << 'i';}
friend ostream& operator<< (ostream & sout, complex c)
{
sout << c.a << '+' << c.b << 'i' << "\n";
return sout;
}
};
main()
{
complex c1;
complex c2(1.0,1.0);
c1.display();
cout << endl;
c2.display();
cout << endl;
cout << c2.imag() << endl;
complex c3 = c2; // this uses the default 'copy constructor'
c3.display();
cout << endl;
cout << c2;
}
The output that I am getting is:
complex no. created.
0+0i
1+1i
1
1+1i
1+1i
complex no. with real part 1 destroyed
complex no. with real part 1 destroyed
complex no. with real part 1 destroyed
complex no. with real part 0 destroyed
Just for the sake of completion, I have tried this on CC as well as g++ compilers. And both of them behave same.