I don't know what's wrong, Do I need define a constructor or just keep a copy constructor? I think It's a issue about shallow and deep copies. Please help, Thank you. When I was debugging, Pop this window
#include <cstring>
#include<iostream>
using namespace std;
class MyString
{
public:
MyString(const char* s); //constructor
~MyString() { //destructor
delete[]data;
}
protected:
unsigned len;
char* data;
//char data[20];
};
MyString::MyString(const char* s)
{
len = strlen(s);
data = new char[len + 1];
strcpy_s(data, len, s);
}
int main()
{
MyString a("C++ Programming");
MyString b(a);
return 0;
}
Currently, you don't have a copy contructor. What you have is a constructor which takes a const char* array.
A copy constructor has the following format:
Putting it all together you can write something like this:
This is happening because when you are using strcpy_s it copies over the null terminate character as well, and if your destination cstring is not large enough it will throw an exception, but once you add 1 to
lenyour destination cstring is going to be of sufficient size.