Friday, 23 August 2013

Vector doesn't create objects properly

Vector doesn't create objects properly

I've created a class with some static datas. Something like this:
class Object
{
public:
Object();
Object( Point center, double area );
Object( int cx, int cy, double area );
~Object();
public stuffs here...
private:
Point center;
double area;
static double totalArea;
static int objCounter;
static double areaMean;
};
than in it's constructor and destructor I made:
Object::Object()
{
this->setCenter( Point() );
this->setArea( 0.0 );
objCounter++;
totalArea += 0;
areaMean = totalArea / objCounter;
}
Object::~Object()
{
//cout << "Destructor called!\n"; //put it just to test
objCounter--;
totalArea -= this->area;
areaMean = totalArea / objCounter;
}
So my intention was to know how many Objects were created, it's total area
and the mean area. I tested it with simple statements like:
Object first;
Object first;
cout << Object::getObjCounter() << "\n";
///I have the get method implement origanally
And everything it's ok. Object class count number of instaces correctly. I
tested using simple arrays:
Object test[ 10 ];
cout << Object::getObjCounter() << "\n";
Amazing... it works, as it should; I tested with dynamic allocation:
Object *test = new Object[ 10 ];
cout << Object::getObjCounter() << "\n";
delete [] test;
Again... it works. But when i try:
vector< Object > test( 10, Object() );
cout << Object::getObjCounter() << "\n";
It gives me zero in the stdout... I put flags in constructor and
destructor to see why it's happening. And it shows me that when I use the
vector statement shown, constructor is called just on, than the destructor
is called in sequence!!!! Why???? Doesn't make sense to me! Could anybody
explain this to me? In addition, could anybody help me in using vector to
achieve the same effect that I have with simple arrays, which means: has a
bunch of objects inside something, and counting it correctly? The thing is
I need vectors functionality like remove and add elements, and resizing,
but I don't want to reinvent wheel. Thank's in advance

No comments:

Post a Comment