Operator overloading for Strings

Refresh

March 2019

Views

820 time

1

I cannot see whats wrong with the codesnippet below where I try to overload the operator "=". I can build it but not run it (it crashes). Its due to the following syntax in the main method:

string2 = "my world!";

As far as I know - on the left handside of the operator is the object that holds the operator overloaded function and recevies the string-literal (that is passed to the function as an argument) on the right side of the operator.

below is the full code:

#include <iostream>
using namespace std;

class String {

public:
char *string;
String(char *ch) {
    string = ch;
}
String (String &string_obj) {
    string = string_obj.string;
}
String operator=(char *ch) {

    strcpy(string, ch);

    return *this;
}

};

ostream &operator<<(ostream &stream, String obj) {

    stream << obj.string;

    return stream;
}



int main() {

   String string("hello ");
   String string2(string);
   cout << string << string2;

   string2 = "my world!";
   cout << string2;



return 0;
}

4 answers

0

Firstly, your String class should have value semantic, and it doesn't. Secondly, you are not allocating any memory for your String.

0

Your code is broken in many ways. If this is for learning purposes, you should take a look at existing implementations of std::string. If you are planning on using that class in production code: don't, and just use std::string.

1

In the operator= you are trying to copy the contents of char* to member variable string, but it can be NULL, it may not have enough memory to hold copied string. There are also other problem in you code like not passing const reference to copy constructor etc. I think you should first learn the basics before trying to overload operators.

1

you are passing a constant literal in function in this line String string("hello "); and when you are doing strcpy inside String operator=(char *ch) it is trying to modify the content of a constant memory location leading the problem to crash.

you can try by doing this

int main() {
   char str[]="hello";    
   String string(str);
   String string2(string);
   cout << string << string2;

   string2 = "my world!";
   cout << string2;



return 0;
}