This is a friend function that takes a char* and a string and concatenates them. In my case this returns them appended in the wrong order.
S7 is defined as Function
S8 is defined as Function 2
The output should return "Friend function 1(2)" but my output from my friend function returns "function 1(2)Friend". How can I reverse this? When I reverse strcat to read strcat(bufferString, stringIn.str); the function breaks. What am I doing wrong here?
When overloading operators, if you have two arguments, the first argument is always on the left side of the operator, and the second argument is always on the right side of the operator. If you only have one argument, such as String1 String1::operator+(arg1) the object (String1) is always on the left side of the operator, and the argument is always on the right side. So, you have to switch your arguments in strcat or in your overloaded operator function call.
String1::String1(bufferString); doesn't do anything. It constructs the String1, then noticing it is no longer referenced, marks it for deletion. If you do something like String1 temp(bufferString);, then you'll have something that's more like what you want.
bufferString is a character pointer. It has a limited amount of space, and you're filling it. This can cause a buffer overflow, and most compilers and operating systems can detect and stop that (you probably got a segfault). You need to give it enough space to concatenate stringIn onto it, or you need to use a different method of concatenation. You could do what you're trying to do in line 11, but actually assign it to a variable, and then you can concatenate using the method you probably already have for concatenating two String1s.
String1 operator+(char *bufferString, String1 &stringIn)
{
String1 S;
String1 temp(bufferString);
temp = S;
//cout << temp;
strcat(S.str, stringIn.str);
cout << S;//checks to see if its concatenating properly now just to return this
return S;
}
So this work and it concatenating the string properly... now in my main how to i get the returned output to display using the function call ("Friend" + String?);
It actually looks like your assignment operator is working incorrectly or something. S shouldn't have anything useful in it, and temp = S; would assign the useless stuff to temp, not the other way around. Also, you aren't handling buffer overflows unless you rewrote strcat. If you have string "ab" and try to strcat "cd", you'll get a buffer overflow where some of your string is in memory that doesn't belong to that string. Your function should probably look like
1 2 3 4 5 6 7
String1 operator+(constchar *bufferString, const String1 &stringIn)
{
String1::String1 temp(bufferString);
//somewhere in here you need to make enough space for the concatenation
strncat(temp.str, stringIn.str, strlen(temp.str) + strlen(stringIn.str) + 1);
return temp;
}