Hi...
I am trying to write a string class...this part is supposed to concatenate two strings, but I am having trouble with constructors/destructors.:rolleyes:
Please explain the exact sequence of calls and the correct way to code.:?:
#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;
class STRING
{
char *str;
int len;
public:
STRING( ) { cout<<"*** Default Constructor called. ***"<<endl; str = NULL, len = 0; }
STRING( const char *s );
STRING( const STRING& );
~STRING( );
friend ostream& operator<<( ostream &os, STRING s );
STRING operator+( STRING &s );
};
STRING::STRING( const char *s )
{
cout<<"*** String constructor called. ***\n";
len = strlen( s );
str = new char[len+1];
strcpy( str, s );
}
STRING::STRING( const STRING& s )
{
cout<<"*** Copy constructor called. ***\n";
len = s.len;
str = new char[len+1];
strcpy( str, s.str );
}
STRING::~STRING( )
{
cout<<"*** Destuctor called. ***"<<endl;
delete[] str;
len = 0;
}
ostream& operator<<( ostream &os, STRING s )
{
if( s.len == 0 )
cout<<"(Empty)\n";
else
os<<s.str<<endl;
return os;
}
STRING STRING::operator+( STRING &s )
{
STRING res;
res.len = len + s.len;
res.str = new char[res.len+1];
strcpy( res.str, str );
strcat( res.str, s.str );
return res;
}
int main( )
{
STRING s1("String1");
STRING s2("String2");
STRING s3;
s3 = s1+s2;
cout<<s1<<s2<<s3;
getch( );
return 0;
}