Answer the question
In order to leave comments, you need to log in
Problem with destructor when using copy constructor?
Everyone, good afternoon! The following question arose while learning c++:
there is a Sea class:
class Sea
{
private:
char* sea_name;
int max_depth;
double square;
public:
void SetSeaName(const char* p)
{
if (strlen(p) != strlen(this->sea_name) || this->sea_name == nullptr)
{
delete[] this->sea_name;
this->sea_name = new char[strlen(p) + 1];
}
strcpy(this->sea_name, p);
}
Sea(const char* arr, int d, double s) :max_depth(d), square(s)
{
this->sea_name = new char[strlen(arr) + 1];
strcpy(this->sea_name, arr);
}
Sea(int d, double s) :Sea("cde", d, s)
{
}
~Sea()
{
delete[] sea_name;
cout << "Destructor" << endl;
}
Sea()
{
this->sea_name = new char[4];
strcpy(this->sea_name, "abc");
this->max_depth = 1000;
this->square = 100000;
}
//Конструктор копирования
Sea(const Sea& param):sea_name(param.sea_name),max_depth(param.max_depth),square(param.square)
{
cout << "Copy Constructor is worked!" << endl;
}
};
int main()
{
setlocale(LC_ALL, NULL);
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
{
Sea s1();
Sea s2("aaaa", 1000, 2000.5);
Sea s3(1000, 200.5);
Sea s4=s3;
Sea s5(100,100);
}
Sea* s4 = new Sea();
s4->~Sea();
system("pause");
return 0;
}
Sea s4=s3;
- when calling the destructor s4. I can’t understand what the problem is (I guess, rather, that the problem is that s3 - the destructor - is called twice, but I don’t know how to avoid this - because it will also be called here ). How many examples I watched on the Internet - in all, about the same, and there are no problems.
Tell me please. Thanks in advance! Sea s3(1000, 200.5);
Answer the question
In order to leave comments, you need to log in
Your problem is not with the destructor, but with the fact that you did not allocate memory for sea_name in the copy constructor, but simply assigned the value of the pointer from the object being copied.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question