user83962
user83962

Reputation: 85

design a string class constructor c++

what is the best way to design a string class constructor? The following constructors definitely have problem: two pointers pointing one object, if one of them is destructed, the other will cause a fatal error. So, what is the best way to design a constructor for a string class?

class CMyString{
    private:
        char *pData;
    public:
        CMyString(char *_p=NULL):pData(_p){
    }
        CMyString(CMyString &_str):pData((_str.pData){
    }
}

Upvotes: 0

Views: 176

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

For example you can define the class the following way.

class CMyString
{
private:
    char *pData;

public:
    CMyString( const char *_p = NULL )
    {
        if ( _p == NULL ) 
        {
            pData = NULL;
        }
        else
        {
            pData = new char[ std::strlen( _p ) + 1 ];
            std::strcpy( pData, _p );
        }
    }

    CMyString( const CMyString &_str )
    {
        if ( _str.pData == NULL ) 
        {
            pData = NULL;
        }
        else
        {
            pData = new char[ std::strlen( _str.pData ) + 1 ];
            std::strcpy( pData, _str.pData );
        }
    }

    explicit operator bool () const { return ( pData != NULL ); } 

    CMyString & operator =( const CMyString & ); // do not forget to define

    ~CMyString(); // do not forget to define
};

Or you can define the copy constructor the following way

    CMyString( const CMyString &_str ) : CMyString( _str.pData )
    {
    }

Upvotes: 2

Brian Bi
Brian Bi

Reputation: 119069

Allocate space and copy the characters over.

Also, I suggest not allowing pData to be null, as it complicates the logic. Instead, if no initial value is given, create an empty string.

Also, don't forget to be const-correct.

CMyString(const char *_p = "") {
    size_t len = strlen(_p);
    pData = new char[len+1];
    strcpy(pData, _p);
}
CMyString(const CMyString& _str) { /* basically the same as above */ }

Upvotes: 1

Related Questions