c++ - Multiple destructor calls -
i ran 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 " << 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
constructor called postfix increment called destructor called prefix increment called destructor called postfix decrement called destructor called destructor called
my question why destructor called many times?
first of 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 return nothing though return types not void. should write example
base operator ++ (int) { count++; cout << "postfix increment called" << endl; return *this; }
otherwise program has undefined behaviour.
as operators have return type base compiler calls destructor temporary objects operators have return.
all these 3 expressions
a++; ++a; a--;
are in fact temporary objects.
Comments
Post a Comment