I am near giving up right now - headache and red eyes. Some of you will probably downvote this question but I have no alternative. I am not lazy but have no one to talk to.
Its all about making my own String-class in c++ where one can be able to concatenate strings, send another string object into the strings constructor, or send string-literals to the constructor.
The program is supposed to output the following:
hello hello2
much hedache!!!
Enter a name:
hello John
Instead the program is producing the following:
hello hello2
much hedache!!!
Enter a name:
much headache John
For somereason the string "much headache" is kept in the object - not substituted with a concatenation of string and string3.
string2 = "much hedache!!!";
And I have noticed that this is somehow caused when I send a string object to the constructor.
String string2(string);
If I now change this to the following:
String string2("hello2");
it works.
I cannot figure out why, would be very delighted of someone could answer this.
#include <iostream>
using namespace std;
class String {
public:
char *string;
String(char *ch) {
string = new char[strlen(ch)];
int i = 0;
for(char *temp_ch_ptr = ch; *temp_ch_ptr; ++temp_ch_ptr) {
string[i] = *temp_ch_ptr;
i++;
}
}
String() {
string = new char[100];
}
String (String &string_obj) {
string = new char[strlen(string_obj.string)];
string = string_obj.string;
}
String operator=(char *ch) {
strcpy(string, ch);
return *this;
}
String operator+(String obj) {
String temp;
strcpy(temp.string, string);
strcat(temp.string, obj.string);
return temp;
}
};
ostream &operator<<(ostream &stream, String obj) {
stream << obj.string;
return stream;
}
istream &operator>>(istream &stream, String obj) {
cout << "Enter a name: ";
stream >> obj.string;
return stream;
}
int main() {
String string("hello ");
//String string2("hello2 ");
String string2(string);
cout << string << string2 << endl;
string2 = "much hedache!!!";
cout << string2 << endl;
String string3;
cin >> string3;
string2 = string + string3;
cout << string2 << endl;
return 0;
}
I am not sure about the copy-constructor - could the problem be there?