I am trying to create a dynamic constructor using character array in c++. But when I try to compile with g++, I am getting an error. Here is my code:
#include <iostream>
#include <cstring>
class Dstring{
private:
char* value;
public:
Dstring(char* val){
value = new char[strlen(val)];
strcpy(value, val);
}
Dstring(Dstring val1, Dstring val2){
value = new char[strlen(val1.value) + strlen(val2.value)];
strcat(value, val1.value);
strcat(value, val2.value);
};
void show(){
std::cout << value << std::endl;
}
~Dstring(){
std::cout << "Delete " << value << std::endl;
delete value;
}
};
int main(){
Dstring str1((char*)"Hello ");
Dstring str2((char*)" World!");
Dstring str3(str1, str2);
str3.show();
return 0;
}
And here is the output:
Delete Hello
Delete World!
Hello World!
Delete Hello World!
Delete ����U
free(): double free detected in tcache 2
Aborted (core dumped)
I am confused on why delete is being called twice. I have studied that we must delete dynamically allocated variables in destructor of the class. What am I missing?