What value to assign to a char* in default constructor c++?

112 views Asked by At

I have a class String and I've made a field char* name, default, parameterized, copy constructor, destructor and overwritten operator =.

My question is how my default constructor should look like for a char*.

Below is part of my code. I use char* because the array should be dynamic:

class String {
    public:
        char* name;
        String(){
            name = new char[0];
        }
        String(char* str){
            name = new char[strlen(str) + 1];
            strcpy(name, str);
        }
        
2

There are 2 answers

2
user12002570 On

how my default constructor should look like for a char*.

You can make a null-terminated array of length one. Also note that you should use member initializer list as shown below:

//use member iniializer list
String():name( new char[1]())
//------------------------^^---->note these parentheses to null terminate
{
}
//use member initializer list
String(char* str):name(new char[strlen(str) + 1])
{
    strcpy(name, str);
}
3
Ted Lyngmo On

First, the constructor taking a char* should really take a const char* or otherwise you won't be able to create Strings from string literals:

String(const char* str) : name(new char[std::strlen(str) + 1]) {
    std::strcpy(name, str);
}

The default constructor could then simply delegate construction to the constructor taking a const char*:

String() : String("") {}

As per the logic in the constructor taking a const char*, the default constructor will then allocate memory for one char which will hold the value of \0.


Though, I would recommend to not use a raw owning pointer but to instead use a std::unique_ptr<char[]> or std::vector<char> to help with the memory management. If you use a unique_ptr you could also add member variables for holding the length/size of the string and also its capacity. If you use a std::vector, you can just make proxy member functions for the vectors size() and capacity() member functions. Example using a std::unique_ptr<char[]>.