0

Let's look at this code. Why can the numbers of destructors called more than constructors?

#include <iostream>
using namespace std;


class B{

    public:
    B(){
        cout << "constructor of B\n";
    }
    ~B(){
        cout << "destructor of B\n";
    }
};


void func(B obj){
}


int main(){
    B obj;
    func(obj);
}

and the output is

constructor of B
destructor of B
destructor of B

I don't understand why the number of destructors called are not the same as the number of constructors called?

la lala
  • 41
  • 2
  • 5
  • 8
    You didn't track the number of copy constructors. If you printed out the value of `this`, along with those messages, you will see something is missing. – PaulMcKenzie May 20 '20 at 07:50
  • If you debug your program using `gdb`, you will see a function you never declared being called: `B::B(const B&)` when you step into `func(obj);`. See [implicitly defined copy-constructor](https://en.cppreference.com/w/cpp/language/copy_constructor) – Jorge Bellon May 20 '20 at 07:56
  • related: https://stackoverflow.com/questions/28716209/what-operators-do-i-have-to-overload-to-see-all-operations-when-passing-an-objec – 463035818_is_not_an_ai May 20 '20 at 08:18
  • Rule 0: **every** constructor call is matched by a destructor call, and **every** destructor call is matched by a constructor call. (Unless you're using `new` and `delete` and messing it up) – Pete Becker May 20 '20 at 13:40

2 Answers2

0

You are passing the object to the function by value. Therefore, a copy of the object is made causing the copy constructor of the object to be invoked. When the function ends execution, the temporary copy of the argument is destroyed which invokes the destructor.

ndubs18
  • 11
  • 2
0

Just changing the signature of the function func() will help you understand something's really missing. Consider this one:

void func(B & obj) { ... }

Here you'll pass the object using by reference and you'll no longer get two destructor message since the class function is directly manipulated and no temporary copied arguments will be invoked.

You should then get something like this output:

construct of B
destructor of B
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • Well, no, they *are* calling the copy constructor right now and they won't if they switch to a reference... – Quentin May 20 '20 at 08:00
  • OP will not understand why the desctructor is called more than expected by changing their code such that the desctuctor is called as expected. You arent really answering the question – 463035818_is_not_an_ai May 20 '20 at 08:41
  • @idclev463035818 I hope he'll understand it by reading the highlighted comment in his question. So I just tried to answer only. – Rohan Bari May 20 '20 at 08:45