Reputation: 3
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;
}
Upvotes: 0
Views: 74
Reputation: 3187
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:
MyString(const MyString& obj)
{
// here you will initialize the char* data array to be of the same size
// and then copy the data to the new array using a loop or strcpy_s
}
Putting it all together you can write something like this:
#include <cstring>
#include<iostream>
using namespace std;
class MyString
{
public:
MyString(const char* s); //constructor
MyString(const MyString& obj); //constructor
~MyString() { //destructor
delete[] data;
}
protected:
unsigned int len;
char* data;
void copy_cstring(const char* s)
{
len = strlen(s);
data = new char[len + 1]; // len + 1 to make room for null terminate \0
int i = 0;
for (i = 0; i < len; ++i)
{
data[i] = s[i];
}
data[i] = '\0'; // add \0 to the back of the string
}
};
MyString::MyString(const char* s)
{
copy_cstring(s);
}
MyString::MyString(const MyString& obj)
{
copy_cstring(obj.data);
}
int main()
{
MyString a("C++ Programming");
MyString b(a);
return 0;
}
When I use strcpy_s(data,len+1,s) to replace strcpy_s(data,len,s). It doesn't pop that. – theprog
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 len
your destination cstring is going to be of sufficient size.
Upvotes: 0
Reputation: 25388
As others have mentioned, you don't have a copy constructor in your code.
A minimal copy constructor would be to delegate to your existing const char *
constructor, like so (put this in the declaration of class MyString
):
MyString (const MyString &s) : MyString (s.data) {}
You should also add a copy assignment operator (rule of 3), if you want to avoid nasty surprises down the line.
Upvotes: 0