#include <iostream>
#include <vector>
using namespace std;
class being
{
private:
int hp;
public:
being();
being(int);
~being();
int hit_points(void);
void set_hp(int);
};
being::being()
{
cout<<"Creating a being."<<endl;
hp=0;
}
being::being(int i)
{
cout<<"Creating a being with "<<i<<"hp."<<endl;
hp=i;
}
being::~being()
{
cout<<"Destroying a being."<<endl;
}
int being::hit_points(void)
{
return hp;
}
void being::set_hp(int i)
{
hp=i;
}
main()
{
int i;
int crit=5;
vector<being> critters(crit);
cout<<"Construction has ended."<<endl;
}
C++ vector of objects problem
Hi all.
When compiling the following
And executing, I get the following output:
Creating a being.
Destroying a being.
Construction has ended.
Destroying a being.
Destroying a being.
Destroying a being.
Destroying a being.
Destroying a being.
Where I was expecting the following:
Creating a being.
Creating a being.
Creating a being.
Creating a being.
Creating a being.
Construction has ended.
Destroying a being.
Destroying a being.
Destroying a being.
Destroying a being.
Destroying a being.
Any ideas?
Edit: use source tags (click edit to view) - ED.
[Edited by - Emmanuel Deloget on August 15, 2007 2:53:04 PM]
The vector creates a temporary being, and then creates crit copies (key word being copies: it uses the copy constructor which is, in this case, the default one provided by the compiler, and is why you don't get any output from them being built) of it, after which point this temporary being falls out of scope and is destroyed (as the vector constructor exits). You then print your "construction has ended" message, and the five beings stored in the vector are destroyed.
To go into a little more detail: that constructor's argument list is actually (int, being = being()). This gives you the flexibility to initialize the vector with non-default beings; but of course the vector constructor can't just call *any* being constructor (how would you tell it parameters to use? OK, pass them along as well, but - how many are there? We'd need either a hard-coded limit, or a variadic function, and both of those are rather opposed to the principles of the standard library design) - instead, you provide a prototype, which it copies.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement