Hi... just making the move from C to C++. Would appreciate an answer to the following question...
I want to overload an operator so that it will join strings and assign the result to another object. I can get these to work, but only if my assignment looks like this:
strtype obj5 = ob1 + ob2; // automatically calls copy constructor
What I really want to do is this:
strtype ob1, ob2, ob5;
...
...
...
obj5 = obj1 + obj2; // crashes; prob. does't call copy constructor.
Here's my code... please take a look. Thanks. I use Dev C++.
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
class strtype {
private:
char *s;
public:
strtype( const strtype & ); // copy constructor
strtype() { s = new char; s = '\0'; }
strtype( char * );
~strtype() { cout << "destructing...\n"; }
friend strtype operator+( strtype &, strtype & );
void print_string() { cout << "string: " << s << "\n"; }
};
strtype::strtype( const strtype &obj ) // copy constructor
{
int len;
len = strlen(obj.s);
s = new char [len];
strcpy(s, obj.s);
}
strtype::strtype( char *string )
{
int len;
len = strlen(string);
s = new char [len];
if( !s ) {
cout << "Allocation Error\n";
exit(1);
}
strcpy(s, string);
}
strtype operator+( strtype &string1, strtype &string2 )
{
int len1, len2;
strtype temp;
len1 = strlen(string1.s);
len2 = strlen(string2.s);
temp.s = new char [len1 + len2];
if( !temp.s )
exit(1);
temp.s = strcat(string1.s, string2.s);
return temp;
}
int main()
{
strtype ob1("string1");
strtype ob2("zebra2");
strtype ob5 = ob1 + ob2; // invokes copy constructor
ob5.print_string();
system("PAUSE");
return 0;
}