can someone plz tell me why does the function assign brings to a compilation error??
Next time give us the compiler errors.
You need to include cstring for strlen, strcpy etc..
You need to initialize s outside of the class (to get it to work, I simply added the line char String::s[255] = {'0'}; right after the class declaration)
this is the compilation error:
Error 1 error LNK2001: unresolved external symbol "private: static char * String::s" (?s@String@@0PADA) c:\Users\Al\documents\visual studio 2012\Projects\ConsoleApplication32\ConsoleApplication32\string.obj ConsoleApplication32
the only reason this memebr is static its because that what i was asked to do in this excerise:/
Because you need to actually define that static variable somewhere, so that it can be instantiated. It's not instantiated when a String object is instantiated, because it's static, so you have to do it in the same way as you would a (*spit*) global variable.
The problem is that `String::s` doesn't exist. A class definition only describes how the class looks like, it doesn't create it.
For regular members creation (or definition) happens when you instatiate the class, as in String s1;.
Static class members are more tricky. Since there is only one you can't create it every time you create an object, so you have to define it only once in a separate piece of code.
That piece of code is usually the source¹ file where the class member functions are defined (class.h -> class.cpp). In your case you only have one file so class definition and members definitions all go there.
The reason why char String::s[255] = {'0'};² made the program compile is because that's how you define static members: having a line like <type> <class>::<name> [initialization] at global scope.
Note that initialization is optional. char String::s[255]; would have worked too, but it's a good idea to always initialize data.
¹ Definitions should not be put in header files because when you compile, each source file #including the header with the definition will try to create the static member. To put it simply, you would end up with multiple copies of `String::s`, but then how can String::assign() know which copy is the actual `s`? It can't, so the compiler doesn't allow you to end up with this situation.
This is called the "One definition rule"