I'm trying to implement a basic string class for educational purposes (I'm told the std::string is mainly complicated template code), I've made a start below but seem to have done something wrong as I have 2 issues, intermittently, the output will never print the "size" (number of characters) at the end, and after getchar executes, and the destructor is called, I get a heap fragmentation error.
I'm not sure what's wrong though as I'm allocating strlen + 1 for the \0
strlen(data) + 1 is an object of type size_t. The size of a that is typically 8 bytes (4 on a 32 bit system).
So the line of code begin = newchar[sizeof(strlen(data)+1)];
is effectively identical to begin = newchar[8];
You're creating an array of size 8(or 4 on a 32 bit system), always. This is very bad. You should be creating an array based on the size of the input string; not based on the size of the data type known as size_t.
Basically, what is that sizeof doing there? It has no business being there.
I'm told the std::string is mainly complicated template code
Using std::string isn't all that complicated. There are reasons why the code itself is.
Learning the basics of string manipulation by creating a custom string class is never a bad thing. IMO the work required to get the custom string class working makes using the C++ library std::string less of a pain.
I started learning C++ by using std::string. No char arrays. Later, after multiple attempts to create a custom string class I appreciated all the work that went into making the C++ library work.
Yeah I'm still going to use std::string for everything, I just wanted to get a handle on how they work behind the scenes a bit. I added a couple more operator overloads (i'm sure the + is very non-elegant), exception handles and used std::copy instead of memcpy, but I'm going to leave it at that and maybe try to make my own iterators and vector next.