Re: very newbie question about object creation count
by "Vijaya Kumar B.H." <bhvijaykumarn@[EMAIL PROTECTED]
>
Mar 31, 2008 at 01:35 PM
It is correct behavious. Destructor should not be called the you have done.
Because this is called automatically when the objects are out of scope.
Hence in your case the destructor is called twice and hence -ve value
"john" <johnmortal.forums@[EMAIL PROTECTED]
> wrote in message
news:013640bf-6ec0-4a5a-a879-3c033ecfc44d@[EMAIL PROTECTED]
>I have not been able to figure out why this ends up with a negative
> object count (the class
> counts how many objects there are). I am sure this is obvious to
> everyone else. Could someone please
> point out why the count is not correct. Sorry to ask such a dumb
> question.
>
> It gives the output:
>
> Constructor called, so we have 1 TestClass objects.
> Destructor called so we will have 0 TestClass objects.
> Destructor called so we will have -1 TestClass objects.
>
> Here is the code:
>
> #include<iostream>
>
>
> class TestClass {
> public:
> static int activeObjects; // How many of this type of
> object were constructed
>
> TestClass() { // default constructor
> activeObjects ++;
> std::cout << "Constructor called, so we have "
> << activeObjects << " TestClass objects.\n";
> }
> TestClass( const TestClass & rhs ) { // copy
> constructor
> activeObjects ++;
> std::cout << "Copy constructor called, so we
> have " << activeObjects << " TestClass objects.\n";
> }
> ~TestClass() { // destructor
> activeObjects--;
> std::cout << "Destructor called so we will have
> " << activeObjects << " TestClass objects.\n";
> }
> };
>
> int TestClass::activeObjects = 0;
>
> int main() {
> TestClass object = TestClass();
> object.~TestClass();
>
> }