Почему деструктор для срабатывает дважды
можете пожалуйста объяснить почему при инициализации объектов класса предка деструктор вызывается дважды ? никак не могу понять , извиняюсь заранее за такой глупый вопрос
ChildClass.h
#pragma once
#include <iostream>
using namespace std;
class ColoredRectangle: public Rectangle
{
protected:
int color;
public:
ColoredRectangle() : Rectangle()
{
cout << "ColoredRectangle()" << endl;
color = 0;
}
ColoredRectangle(int width, int height,int color) : Rectangle(width,height)
{
cout << "ColoredRectangle(int width, int height,int color)" << endl;
this->color = color;
}
ColoredRectangle(const ColoredRectangle& p)
{
cout << "ColoredRectangle(const ColoredRectangle& p)" << endl;
color = p.color;
width = p.width;
height = p.height;
}
~ColoredRectangle()
{
cout << width << " " << height << " " <<"color = " << color << endl;
cout << "~ColoredRectangle()" << endl;
}
void changeColor(int new_color)
{
color = new_color;
}
};
mainClass.h
#pragma once
#include <iostream>
using namespace std;
class Rectangle
{
protected:
int width, height;
public:
Rectangle()
{
cout << "Rectangle()" << endl;
width = 0;
height = 0;
}
Rectangle(int width, int height)
{
cout << "Rectangle(int width,int height)" << endl;
this->width = width;
this->height = height;
}
Rectangle(const Rectangle& p)
{
cout << "Rectangle(const Rectangle &p)" << endl;
width = p.width;
height = p.height;
}
~Rectangle()
{
cout << width << " " << height << endl;
cout << "~Rectangle()" << endl;
}
void changeSize(int deltWidth, int deltHeight)
{
width += deltWidth;
height += deltHeight;
}
void resetSize();
};
void Rectangle::resetSize()
{
width = 0;
height = 0;
}
source.cpp
#include <iostream>
#include "mainClass.h"
#include "ChildClass.h"
using namespace std;
int main()
{
setlocale(LC_ALL, "rus");
int choice;
for (;;)
{
cout << "Вызвать методы changeSize или resetSize(для статич. и динамич. объектов)" << endl;
cout << "1.changeSize\n2.resetSize" << endl;
cout << "3.Определить объект класса-наследника" << endl;
cin >> choice;
switch (choice)
{
case 1:
{
Rectangle p;
Rectangle p1(10, 20);
Rectangle p2(p1);
cout << "Вызов метода changeSize" << endl;
p1.changeSize(35, -10);
}
case 2:
{
Rectangle* p4 = new Rectangle;
Rectangle* p5 = new Rectangle(20, 40);
Rectangle* p6 = new Rectangle(*p5);
//cout << "Вызов метода resetsize" << endl;
//p6->resetSize();
delete p4;
delete p5;
delete p6;
}
case 3:
{
ColoredRectangle* p7 = new ColoredRectangle(5, 10, 30);
delete p7;
}
}
}