I am trying this program
#include<iostream>
#include<string.h>
class stringTest
{
char* p;
int len;
public:
stringTest() { len = 0; p = 0; }
stringTest(const char* s);
stringTest(const stringTest& s);
~stringTest() { delete p; }
friend stringTest operator+(const stringTest& s, const stringTest& t);
friend int operator<=(const stringTest& s, const stringTest& t);
friend void show(const stringTest s);
};
stringTest::stringTest(const char* s)
{
len = strlen(s);
p = new char[len + 1];
strcpy(p, s);
}
stringTest::stringTest(const stringTest& s)
{
len = s.len;
p = new char[len + 1];
strcpy(p, s.p);
}
stringTest operator+(const stringTest &s, const stringTest &t)
{
stringTest temp;
temp.len = s.len + t.len;
temp.p = new char[temp.len + 1];
strcpy(temp.p, s.p);
strcat(temp.p, t.p);
return (temp);
}
int operator<=(const stringTest& s, const stringTest& t)
{
int m = strlen(s.p);
int n = strlen(t.p);
if (m <= n) return (1);
else return (0);
}
void show(const stringTest s)
{
cout << s.p;
}
int main()
{
stringTest s1 = "New ";
stringTest s2 = "York";
stringTest s3 = "Delhi";
stringTest string1, string2, string3;
string1 = s1;
string2 = s2;
string3 = s1+s2;
cout << "\nstirng1 = "; show(string1);
cout << "\nstring2 = "; show(string2);
cout << "\n";
cout << "\nstring3 = "; show(string3);
cout << "\n\n";
if (string1 <= string3)
{
show(string1);
cout << " smaller than ";
show(string3);
cout << "\n";
}
else
{
show(string3);
cout << " smaller than ";
show(string1);
cout << "\n";
}
return 0;
}
here in the function operator+ I am providing two string and getting an junk character in return.
stringTest operator+(const stringTest &s, const stringTest &t)
{
stringTest temp;
temp.len = s.len + t.len;
temp.p = new char[temp.len + 1];
strcpy(temp.p, s.p);
strcat(temp.p, t.p);
return (temp);
}
I debugged the code and saw in the memory i am able to get the proper data in temp.p but when i return it become junk character . Please help me if i am missing something.
Thanks in advance
Vivek