2

I am writing my own String.h for learning purpose.

I am trying to implementing the following :

String s = "Hello World"; //This works

s += " Hi"; // Should be "Hello World Hi"

The following is my operator overload:

String& operator+=(const char* rhs)
    {
        size_t length = m_length + strlen(rhs);
        char* string = new char[length + 1];
        strncpy_s(string, length + 1, m_string, m_length);
        String s = string;
        std::cout << "Concat String : " << s << "\n"; //This prints correctly
        return s;
    }

And my constructor :

String(const char* string)
    {
        if (!string)
        {
            m_length = 0;
            m_string = new char[0];
        }
        else
        {
            m_length = strlen(string);
            m_string = new char[m_length + 1];
            strncpy_s(m_string, m_length+1,string,m_length);
        }
    }

This is my << overload :

std::ostream& operator<<(std::ostream& out, String& string)
{
    out << string.m_string;
    return out;
}

The issue : When I print cout << s; in the operator+= it is printing correctly but in the main function where I am calling it :

String s = "Hello World";
s += " Hi";
std::cout << s;

It is coming as "Hello World".

Please help. I am still on my learning path. Thanks in advance.

Thomas A Mathew
  • 167
  • 1
  • 13

0 Answers0