R
rahul8143
hello,
I write a following program and have problem in understanding
constructors and destructors.
#include <iostream.h>
class vector
{
public:
double x;
double y;
static int cnt,dst;
vector (double = 0, double = 0);
~vector ();
vector operator + (vector);
};
int vector::cnt=1;
int vector::dst=1;
vector::~vector ()
{
cout<<"called destructor "<<dst++<<"times\n";
}
vector::vector (double a, double b)
{
cout<<"called constructor "<<cnt++<<"times\n";
x = a;
y = b;
}
vector vector:
perator + (vector a)
{
return vector (x + a.x, y + a.y);
}
ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")\n";
return o;
}
int main ()
{
vector a;
vector b;
vector c (3, 5);
a = b + c;
cout << "The content of vector a: " << a;
return 0;
}
/*
called constructor 1times
called constructor 2times
called constructor 3times
called constructor 4times
called destructor 1times
called destructor 2times
The content of vector a: (3, 5)
called destructor 3times
called destructor 4times
called destructor 5times
called destructor 6times
*/
constructor 4 but why this function corresponds to 2 destructor
functions?
Again it can be easily understood that constructors 1,2,3 has
corresponding destructors 4,5,6 then for what purpose destructor 3
called.
I am referring my output for numbering constructors and destructors.
I write a following program and have problem in understanding
constructors and destructors.
#include <iostream.h>
class vector
{
public:
double x;
double y;
static int cnt,dst;
vector (double = 0, double = 0);
~vector ();
vector operator + (vector);
};
int vector::cnt=1;
int vector::dst=1;
vector::~vector ()
{
cout<<"called destructor "<<dst++<<"times\n";
}
vector::vector (double a, double b)
{
cout<<"called constructor "<<cnt++<<"times\n";
x = a;
y = b;
}
vector vector:
{
return vector (x + a.x, y + a.y);
}
ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")\n";
return o;
}
int main ()
{
vector a;
vector b;
vector c (3, 5);
a = b + c;
cout << "The content of vector a: " << a;
return 0;
}
/*
called constructor 1times
called constructor 2times
called constructor 3times
called constructor 4times
called destructor 1times
called destructor 2times
The content of vector a: (3, 5)
called destructor 3times
called destructor 4times
called destructor 5times
called destructor 6times
*/
constructors 1,2,3 then function operator + (vector a) callsFrom above program what i get is that class objects a,b,c calls
constructor 4 but why this function corresponds to 2 destructor
functions?
Again it can be easily understood that constructors 1,2,3 has
corresponding destructors 4,5,6 then for what purpose destructor 3
called.
I am referring my output for numbering constructors and destructors.