C++ vector of objects problem

Recommended Posts

Hi all. When compiling the following
#include &lt;iostream&gt;
#include &lt;vector&gt;
using namespace std;

class being
{
private:
int hp;
public:
being();
being(int);
~being();
int hit_points(void);
void set_hp(int);
};

being::being()
{
cout&lt;&lt;"Creating a being."&lt;&lt;endl;
hp=0;
}

being::being(int i)
{
cout&lt;&lt;"Creating a being with "&lt;&lt;i&lt;&lt;"hp."&lt;&lt;endl;
hp=i;
}

being::~being()
{
cout&lt;&lt;"Destroying a being."&lt;&lt;endl;
}

int being::hit_points(void)
{
return hp;
}

void being::set_hp(int i)
{
hp=i;
}

main()
{
int i;
int crit=5;
vector&lt;being&gt; critters(crit);
cout&lt;&lt;"Construction has ended."&lt;&lt;endl;
}


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]

Share on other sites
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.

Many thanks !

Share on other sites
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.

Create an account

Register a new account

• Forum Statistics

• Total Topics
627702
• Total Posts
2978712

• 21
• 14
• 12
• 10
• 12