Very simple C++ string class in 31 lines

Bismillah

Its 2 things what I learnt

 1: #include <stdio.h>
 2: #include <stdlib.h>

 3: class cstring {
 4: private :
 5:  short int i;
 6:  short int maxl;
 7:  char * data;
 8: public:
 9:  short int len;
10:  char *str;

11:  cstring()  { data = (char*) malloc( 1024); str = data; maxl = 1024; };
12:  cstring( char * c ) {  data = (char*) malloc( 1024); str = data; maxl = 1024;  strcopy( str, c ); };  // lesson 1
13:  ~cstring() { free( data );  };

14:  cstring& operator = ( char * c ) { strcopy( str, c ); return *this; };

15:  void strcopy( char * dest, char * src ) {
16:    i = 0;
17:    while( (*src != '') && (i++ < maxl) )
18:      *(dest++) = *(src++);
19:    *(dest++) = *(src++);
20:    len = i;
21:  };
22: };

23: void main() {
24:   cstring b;
25:   b = " world";                               // b.operator=( "world" );   // lesson 2
26:   printf( "%d %s\n", b.len, b.str );
27:   cstring c[] = { "hi", "there" } ;
30:   printf( "%s %d\n", c[0].str, c[1].len );
31: }

Lessons learn:

  1. You can NOT call constuctor line 11 in line 12 , ie: cstring(); because its not what you mean. Compiler will interpret it as Object creation. My friend told me that he ever do similar code but forgot how to avoid duplicate code in line 11 and line 12. Anyone have idea ?
  2. b.operator= is function name

References:

  1. http://www.cplusplus.com/doc/tutorial/classes2.html
  2. http://csl.sublevel3.org/programming/my_string/

Can someone point out what wrong with my understanding. Thanks

Advertisements