C++ string class design and implementation


 
Thread Tools Search this Thread
Top Forums Programming C++ string class design and implementation
# 1  
Old 09-26-2013
C++ string class design and implementation

Hi,

I am designing the look-alike C++ string class:

Code:
#include <iostream>
#include <cstring>
#include <exception>
#include <new>
#define ALLOC(N) (char*) new char[sizeof(char)*(N)]
#define DELETE(P) delete[] ((char*)(P))

class String {
public:
    // conversions: to C-like type char 
    operator const char*() const { return _str; }

    explicit String(const char* s = (char*)0) {
        if (s) {
            try {
                if (!(_str = new char[strlen(s) + 1])) {
                    std::bad_alloc ba;
                    throw ba;
                }
                strcpy(_str, s);
            } catch (std::exception e) {
                std::cout << e.what() << std::endl;
            }
        } else {
            _str = new char[1];
            *_str = 0;
        }
    }

    /*String (const String& obj) : _str(NULL) {
        if (obj._str) {
            this->_str = new char[strlen(obj._str) + 1];
            strcpy(_str, obj._str);
        } 
    }*/


    String (const String& obj) : _str(new char[obj.len() + 1]) {
        strcpy(_str, obj._str);
    }

    virtual ~String() {
        delete [] ((char*) _str);
        _str = NULL;
    }

    bool operator != (const String& obj) {
        if (this != &obj) return true;
        else return false;
    }

    String& operator = (const String& rhs) {
        if (this != &rhs) /* self assignment check */ {
            this->~String(); // delete[] _str; 
            if (strlen(rhs._str)) {
                _str = new char[strlen(rhs._str) + 1];
                strcpy(_str, rhs._str);
            }
        }
        return *this;
    }

    String& operator = (const char* rhs) {
        this->~String();
        if (strlen(rhs)) {
            _str = new char[strlen(rhs) + 1];
            strcpy(_str, rhs);
        }
        return *this;
    }

   String& operator += (const String& str) {
      // char *temp = new char[strlen(this->str) + strlen(obj.str) ? strlen(obj.str) : 0 + 1];
     /*  if (str) {
          char *temp = new char[strlen(str)];
          strcpy(temp, str);
      delete [] ((char *) str);
          str = new char[strlen(this->str) + strlen(obj.str) ? strlen(obj.str) : 0 + 1];
      strcpy(str, temp);
      if (strlen(obj.str)) strcat(str, obj.str);
       } else {
          str = new char[strlen(obj.str) ? strlen(obj.str) : 0 + 1];
      if (strlen(obj.str)) strcpy(str, obj.str);
       }*/
       return *this;
   }


    String& operator + (const String& obj) {
        return operator += (obj);
    }

    int strlen(const char *s) {
        if (!s) return 0;
        const char *tmp = s;
        while (*s) s++;
        return s - tmp;
    }

    void strcpy(char *dest, const char *src) {
        while ((*dest++ = *src++));
    }

    size_t len() const {
        return strlen(this->_str);
    }

    char* retString() const { return _str; }

private:
    char* _str;
};


int main() {
    String obj1("World");
    //   String obj2("Ibrahim");
    String obj2(obj1);
    //   obj1 +=" ";
    //obj1 += obj2;
    std::cout << obj1.retString() << std::endl;
    std::cout << obj2.retString() << std::endl;
}

When compiling the code, I am getting the error
string.cpp: In member function ‘size_t String::len() const':
string.cpp:105:33: error: passing ‘const String' as ‘this' argument of ‘int String::strlen(const char*)' discards qualifiers


Could anyone help me to fix this problem?
for a temporary workaround I am using the
Code:
 return ::strlen(this->_str);

# 2  
Old 09-26-2013
Calling a member function "const" is to guarantee to the compiler "this function modifies absolutely nothing in this class". You are calling a non-const member function(strlen) from a const member function, hence the error.

Which is to say, if you made your strlen() member const too, the error should stop.

'retstring' should be returning 'const char *'.

I'm not sure why you bothered making strlen() when you could have just #include <stdio.h>.

Last edited by Corona688; 09-26-2013 at 01:19 PM..
These 2 Users Gave Thanks to Corona688 For This Post:
# 3  
Old 10-01-2013
Thanks Corona688, your solution worked Smilie, just wanted to know why in string class we need an 'explicit' constructor? any thoughts on this....
Login or Register to Ask a Question

Previous Thread | Next Thread

8 More Discussions You Might Find Interesting

1. Programming

C++ : Base class member function not accessible from derived class

Hello All, I am a learner in C++. I was testing my inheritance knowledge with following piece of code. #include <iostream> using namespace std; class base { public : void display() { cout << "In base display()" << endl; } void display(int k) {... (2 Replies)
Discussion started by: anand.shah
2 Replies

2. Shell Programming and Scripting

Match string against character class in bash

Hello, I want to check whether string has only numeric characters. The following code doesn't work for me #!/usr/local/bin/bash if ]]; then echo "true" else echo "False" fi # ./yyy '346' False # ./yyy 'aaa' False I'm searching for solution using character classes, not regex.... (5 Replies)
Discussion started by: urello
5 Replies

3. Programming

Size of Derived class, upon virtual base class inheritance

I have the two class definition as follows. class A { public: int a; }; class B : virtual public A{ }; The size of class A is shown as 4, and size of class B is shown as 16. Why is this effect ?. (2 Replies)
Discussion started by: techmonk
2 Replies

4. UNIX for Advanced & Expert Users

Get pointer for existing device class (struct class) in Linux kernel module

Hi all! I am trying to register a device in an existing device class, but I am having trouble getting the pointer to an existing class. I can create a class in a module, get the pointer to it and then use it to register the device with: *cl = class_create(THIS_MODULE, className);... (0 Replies)
Discussion started by: hdaniel@ualg.pt
0 Replies

5. Shell Programming and Scripting

Design Search string

I've notepad in which logs are present. I need to design a web page by which if some one paste their ticket number and click on "search" the logs for that ticket number should be displayed at the bottom. I need some advice on how to do this and which is the right platform to do this. Regards... (1 Reply)
Discussion started by: ilugopal
1 Replies

6. Shell Programming and Scripting

[Python]StringVar() Class String processing

I have a requirement where I collect inputs from entry widget in gui(via variables a,b,c) and then output a string like this: -a a -b b -c c. Hence if I have given a=1 b=2 c=3, The output string is --> -a 1 -b 2 -c 3 or if I have given a=1 b=2 (c left blank) then the output is --> -a 1... (1 Reply)
Discussion started by: animesharma
1 Replies

7. Programming

C++ class definition with a member of the same class

Hi, i have a question about C++. Is it possible to declare a class with a member ot the same class? For example, a linked list or i want to convert this C code to C++ class (Elemento) typedef struct elemento { char name; char value; List<struct elemento> ltElementos; ... (7 Replies)
Discussion started by: pogdorica
7 Replies

8. Programming

C++ class design

Can anybody tell me what is the best website or books to read for getting good knowledge in doing C++ class design. Please leave cplusplus.com or bjorne stroustrup. Other than these is there any website or book. Please do tell me (0 Replies)
Discussion started by: dhanamurthy
0 Replies
Login or Register to Ask a Question