S
subramanian100in
Consider the following program:
#include <iostream>
#include <vector>
using namespace std;
class Test
{
public:
Test();
friend ostream &operator <<(ostream &os, const Test &t);
private:
static int counter;
int value;
};
int Test::counter = 0;
Test::Test()
{
value = ++counter;
cout << "from default ctor " << value << endl;
}
ostream &operator <<(ostream &os, const Test &t)
{
os << t.value;
return os;
}
int main()
{
vector<Test> tvec(10);
for (vector<Test>::iterator iter = tvec.begin();
iter != tvec.end();
++iter)
cout << *iter << endl;
return 0;
}
When I compile and run this program under VC++ 2005 Express Edition,
it prints the following
from default ctor 1
1
1
1
1
1
1
1
1
1
1
The default ctor is called only once.I thought default ctor should be
called 10 times because the statement contains tvec(10) as in
vector<Test> tvec(10);
Where am I going wrong.
Also every Test object in tvec has the same value 1. Why is it so ?
Kindly explain.
Thanks
V.Subramanian
#include <iostream>
#include <vector>
using namespace std;
class Test
{
public:
Test();
friend ostream &operator <<(ostream &os, const Test &t);
private:
static int counter;
int value;
};
int Test::counter = 0;
Test::Test()
{
value = ++counter;
cout << "from default ctor " << value << endl;
}
ostream &operator <<(ostream &os, const Test &t)
{
os << t.value;
return os;
}
int main()
{
vector<Test> tvec(10);
for (vector<Test>::iterator iter = tvec.begin();
iter != tvec.end();
++iter)
cout << *iter << endl;
return 0;
}
When I compile and run this program under VC++ 2005 Express Edition,
it prints the following
from default ctor 1
1
1
1
1
1
1
1
1
1
1
The default ctor is called only once.I thought default ctor should be
called 10 times because the statement contains tvec(10) as in
vector<Test> tvec(10);
Where am I going wrong.
Also every Test object in tvec has the same value 1. Why is it so ?
Kindly explain.
Thanks
V.Subramanian