Adam Mo
Adam Mo

Reputation: 75

C++ overloading += operator with double pointers

So I'm trying to overload the += operator for a dictionary program assignment. This is my function:

Definition& Definition::operator += (const String& input) {
    String** temp;
    temp = new String*[numDefs + 1];
    temp[0] = new String[numDefs];
    for (int i = 0; i < numDefs; i++)   {
            temp[i] = def[i];
    }
    temp[0][numDefs] = input;
    delete[] def;
    def = temp;
    numDefs++;
    return *this;
}

However when I try to put 'input' into 'temp' it doesn't seem to work. This is my String class function for allocating string to string:

String& String::operator=(const String& input) {
    data = NULL;
    (*this) = input.getData();
    return *this;
}

and:

String& String::operator=(const char* input) {
    if (data != input)
    {
        if (data != NULL)
        {
            delete[] data;
            data = NULL;
        }
        data_len = strSize(input);
        if (input != NULL)
        {
            data = new char[data_len + 1];
            strCopy(data, input);
        }
    }
    return *this;
}

Can't seem to find the problem.

Upvotes: 0

Views: 345

Answers (1)

Adam Mo
Adam Mo

Reputation: 75

There was an answer posted a minute ago that the user deleted and helped me, I changed the code to:

Definition& Definition::operator += (const String& input) {
    String** temp;
    int tempSize = numDefs + 1;
    temp = new String*[tempSize];
    for (int i = 0; i < numDefs; i++)   {
        temp[i] = new String;
        temp[i] = def[i];
    }
    temp[numDefs] = new String;
    (*temp[numDefs]) = input;
    delete[] def;
    def = temp;
    numDefs = tempSize;
    return *this;
}

Whoever it was, Thanks!

Upvotes: 1

Related Questions