C++ Trouble Understanding Destructor Call

81 views Asked by At

This program is designed with custom class A which outputs 1 when the copy constructor is called, and 0 when the destructor is called.

I copied twice, and deleted twice, yet the destructor was called 3 times, resulting in an output of 11000. Why is this the case?

#include <iostream>
using namespace std;

class A {
public:
    float v;
    A() {v = 1.0;}
    A(A &a) {A::v = a.v; cout << "1";}
    ~A() { cout << "0";}
    float set(float v){
        A::v = v;
        return v;
    }
    float get(float v){
        return A::v;
    }
};

int main(){
    A a, *b = new A(a), *c = new A(*b); // output 110 (Not sure why the destructor is called in this line)
    c->get(b->get(a.set(1.0)));
    delete b; // output 0 
    delete c; // output 0
    return 0;
}

I tried commenting out lines of code, and through doing so have narrowed down the extra destructor call to this line:

A a, *b = new A(a), *c = new A(*b);

However, I still don't understand why the destructor is being called here.

2

There are 2 answers

0
463035818_is_not_an_ai On

The destructor isn't called in that line. It is called when A a is destroyed. You can get a better view of what's happening when you distinguish the different objects by initializing the member with different value:

#include <iostream>


class A {
public:
    int v;
    A(int v) : v(v)  {}
    ~A() { std::cout << v;}
};

int main(){
    A a(1), *b = new A(2), *c = new A(3);
    delete b; 
    delete c; 
    std::cout << "bye \n";
    return 0;
}

output is:

23bye 
1

delete b prints 2, delete c prints 3, std::cout << "bye \n" prints bye and when main returns a is destroyed too which prints 1.

0
vinc13e On

You have 3 objects of class A. a - constructed with default constructor, so '1' is not printed. b, c - constructed with copy constructor that prints '1'.

So you are printing '1' only for b,c.

The destructor is called for all a,b,c. For b,c you are calling it explicitly and for a D'tor is called when function (main in this case) exits.