vendredi 29 mai 2015

Multiple destructor calls

I ran the following code..

#include <iostream>
using namespace std;

class Base
{
protected:
    int count=0;
public:
    Base() { cout << "Constructor called" << endl; }
    ~Base() { cout << "Destructor called" << endl; }
    int getCount() {cout << "The count value is " << count << endl;}
    Base operator ++ (int) {count++;  cout << "Postfix increment called" << endl;}
    Base operator ++ () {count++;  cout << "Prefix increment called" << endl;}
};

class Derived : public Base
{
public:
    Base operator --(int)  {count--;  cout << "Postfix decrement called" << endl;}
};

int main()
{
    Derived A;
    A++;
    ++A;
    A--;
    return 0;
}

The result I get is

Constructor called Postfix increment called Destructor called Prefix increment called Destructor called Postfix decrement called Destructor called Destructor called

My question is why the destructor called so many times.

Aucun commentaire:

Enregistrer un commentaire