Sathish
Sathish

Reputation: 237

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?

Upvotes: 0

Views: 673

Answers (4)

AnT stands with Russia
AnT stands with Russia

Reputation: 320551

Conceptually, each of your operators returns a temporary object of type Base to the caller. That temporary object is destroyed after each operator call. This destruction is exactly what you observe in your experiments.

However, you forgot to include return statements into your operator definitions. Because of that you code has undefined behavior.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

First of all all these operators

Base operator ++ (int) {count++;  cout << "Postfix increment called" << endl;}
Base operator ++ () {count++;  cout << "Prefix increment called" << endl;}
Base operator --(int)  {count--;  cout << "Postfix decrement called" << endl;}

are invalid because they return nothing though their return types are not void. You should write for example

Base operator ++ (int) 
{
    count++;  
    cout << "Postfix increment called" << endl;
    return *this;
}

Otherwise the program has undefined behaviour.

As the operators have return type Base then the compiler calls the destructor for the temporary objects that the operators have to return.

All these three expressions

A++;
++A;
A--;

are in fact temporary objects.

Upvotes: 2

user3790646
user3790646

Reputation:

When a variable is passed as a non-reference variable, the compiler creates the variable with the set copy-constructor and destroys it after its scope ends.

To fix that you could pass the variable as a reference.

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180660

Your operators return a Base. Since you do not capture that Base it is destroyed at the end of the expression. Since you have three expressions you are getting three destructor calls.

Upvotes: 0

Related Questions