Search code examples
c++destroy

Why are these points destroyed three times?


Here is the code

#include <iostream>
#include <stdio.h>
using namespace std;

class Point {
    private:
        int x;
        int y;
    public:
        Point(int x, int y) : x(x), y(y) {}
        ~Point() {
            printf("Point destroyed: (%d, %d)\n", x, y);
        }
};

class Square {
    private:
        Point upperleft;
        Point lowerright;
    public:
        Square(int x1, int y1, int x2, int y2) : upperleft(x1, y1), lowerright(x2, y2) {}
        Square(Point p1, Point p2) : upperleft(p1), lowerright(p2) {}
        ~Square() {
            printf("Square destroyed.\n");
        }
};

int main(int argc, char const* argv[])
{
    Point p1(1, 2);
    Point p2(3, 4);
    Square s1(p1, p2);
    return 0;
}

After compile (g++ x.cpp) and run, I got the following results:

Point destroyed: (1, 2)
Point destroyed: (3, 4)
Square destroyed.
Point destroyed: (3, 4)
Point destroyed: (1, 2)
Point destroyed: (3, 4)
Point destroyed: (1, 2)

I expect each Point to be destroyed twice, but they are destroyed three times instead. Why?


Solution

  • Because

    Square(Point p1, Point p2)
    

    takes arguments passed by value which creates a copy of the parameters you pass to it. So you have

    1. The original parameters
    2. The copies passed to the Square constructor
    3. The member variables of the instance of Square you create

    3 instances.