Destructor in C++

Asked

Viewed 218 times

3

In solving some issues in C++, I came across the code:

class MinhaClasse{
private:
       int a;
public:
     MinhaClasse(int b){
        a = b;
       ImprimeA();
       };
    ~MinhaClasse(){
       IncrementaA();
       ImprimeA();
     };
   void IncrementaA(){
       a++;
       };
   void ImprimeA(){
    printf("[%d]", a);
    };
  };
    
 int main(){
   MinhaClasse * mClasseD = new MinhaClasse(1);
   MinhaClasse mClasseE(10);
   return 0;
}

Exit:

[1][10][11] 

However, when removing the destructor ~MinhaClasse(), the exit becomes:

[1][10]

I read some concepts about destructor and some questions, about the theme, among them:

  1. What good is a destroyer?
  2. Doubt about a C++ function that works like a destructor?

However I follow without understanding very well this code, why when the destroyer is removed my exit changes?

2 answers

5


Let’s see your main:

 int main(){
   MinhaClasse * mClasseD = new MinhaClasse(1);    // A
   MinhaClasse mClasseE(10);                       // B
   return 0;                                       // C
}

In line A, you create an instance in heap and assign it on a pointer. As it is in the heap it is your responsibility to remove it explicitly.

In line B, you create an instance in stack and in this case the compiler puts the memory management automatically.

When the function ends (in C), all variables in the stack are destroyed. As the class MinhaClasse has a destructor and that means the object mClasseE will be destroyed, the compiler will place a call to his destructor to be able to clean the stack.

However, in the case of mClasseD, the responsibility to destroy the object is the programmer (with delete mClasseD;). But as you did not, the result is that the object is not destroyed and becomes one memory Leak.

See more in that question to understand what exactly is the heap and the stack.

  • Got it Victor! Thank you very much! I’m going to take a look at Heap and Stack, thanks again

4

Because when leaving the main scope the object mClasseE dies, thus calling the destructor of its class, which increases and prints, as the value of a was 10 shows 11.

Already the object mClasseD does not call the destructor because you created it with the new and the destructor in that case is not called, you must "wipe" the memory using the delete for this object because otherwise your code will have memory leakage. When the delete is called to the object mClasseD the class destructor will be called.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.