Hello. I have been trying to create a program to concatenate two strings using operator overloading for a class STRING. The output I get consists of random characters. Please tell me why this should happen.
Code:
/*
Program to create a class string, which has a provision to concatenate two strings.
*/
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
void nullify(char *,int);
class STRING
{
private:
char *p;
int len,allocated;
public:
STRING();
STRING(char *);
friend STRING operator+(STRING,STRING);
void getstring();
void showstring();
~STRING();
};
STRING::STRING()
{
len=0;
p=new char[1]; nullify(p,1);
allocated=1;
}
STRING::STRING(char *str)
{
if(allocated==1)
delete p;
len=strlen(str);
p=new char[len+1]; nullify(p,len+1); allocated=1;
strcpy(p,str);
}
STRING operator+(STRING s1,STRING s2)
{
STRING sum;
char *temp=new char[s1.len+s2.len+1]; nullify(temp,s1.len+s2.len+1);
strcpy(temp,s1.p); strcat(temp,s2.p);
sum=STRING(temp);
delete temp;
return(sum);
}
void STRING::getstring()
{
if(allocated==1)
delete p;
p=new char[256]; nullify(p,256);
gets(p);
}
void STRING::showstring()
{
cout<<p;
}
STRING::~STRING()
{
if(allocated==1)
delete p;
}
int main()
{
clrscr();
STRING s1,s2,s3;
cout<<"Enter the first string:"; s1.getstring();
cout<<"Enter the second string:"; s2.getstring();
s3=s1+s2;
cout<<"The concatenated string is:"; s3.showstring();
cout<<endl<<endl<<"PRESS A KEY..."; getch();
return(0);
}
void nullify(char *str,int limit)
{
int ctr;
for(ctr=0; ctr<limit; ++ctr)
str[ctr]=char(0);
}
Compiler : Borland C++ 5.5