/*Program to do manipulations on a string*/
#include <iostream>
using namespace std;
class String
{
int len;
char *p;
public:
String ()
{
cout << "default constructor " << this << endl;
len = 0;
p = NULL;
}
String (const char *s)
{
cout << "String constructor called " << s << endl;
len = strlen(s);
p = new char[len + 1];
strcpy(p, s);
}
String (const String &s)
{
cout << "Copy constructor invoked " << s.p << endl;;
len = s.len;
p = new char[len + 1];
strcpy(p, s.p);
}
~String ()
{
cout << "deleting " << p << " " << this << endl;
delete p;
}
void display(void)
{
cout << p << "\t address of p = " << &p << "\tobject this = " << this << endl;
}
// friend String operator + (const String &s, const String &t);
String operator + (const String &t);
friend int operator <= (const String &s, const String &t);
friend void show (const String &s);
};
String String :: operator + (const String &t)
{
String temp;
cout << "Entered operator+() " << &temp << endl;
temp.len = len + t.len;
temp.p = new char[temp.len + 1];
strcpy(temp.p, p);
strcat(temp.p, t.p);
temp.display();
cout << "Exiting operator+() " << &temp << endl;
return temp;
}
void show (const String &s)
{
cout << s.p;
}
main()
{
String s1("Sidharth") , s2("Sweeya ");
String s3;
//String s3 = s2 + s1;
s3 = s2 + s1;
s1.display();
s2.display();
s3.display();
return 0;
}
Output of the program:
String constructor called Sidharth
String constructor called Sweeya
default constructor 0xbff06c50
default constructor 0xbff06c40
Entered operator+() 0xbff06c40
Sweeya Sidharth address of p = 0xbff06c44 object this = 0xbff06c40
Exiting operator+() 0xbff06c40
deleting Sweeya Sidharth 0xbff06c40
Sidharth address of p = 0xbff06c74 object this = 0xbff06c70
Sweeya address of p = 0xbff06c64 object this = 0xbff06c60
address of p = 0xbff06c54 object this = 0xbff06c50
deleting 0xbff06c50
*** glibc detected *** double free or corruption (fasttop): 0x09e83028 ***
Aborted (core dumped)
If I change the code in the main to
main()
{
String s1("Sidharth") , s2("Sweeya ");
//String s3;
String s3 = s2 + s1;
//s3 = s2 + s1;
s1.display();
s2.display();
s3.display();
return 0;
}
Ouput:
String constructor called Sidharth
String constructor called Sweeya
default constructor 0xbffab2b0
Entered operator+() 0xbffab2b0
Sweeya Sidharth address of p = 0xbffab2b4 object this = 0xbffab2b0
Exiting operator+() 0xbffab2b0
Sidharth address of p = 0xbffab2d4 object this = 0xbffab2d0
Sweeya address of p = 0xbffab2c4 object this = 0xbffab2c0
Sweeya Sidharth address of p = 0xbffab2b4 object this = 0xbffab2b0
deleting Sweeya Sidharth 0xbffab2b0
deleting Sweeya 0xbffab2c0
deleting Sidharth 0xbffab2d0
In the first case the destructor is being called for the temp variable in the operator + function. But in the second case why is not called?
In the second case if copy constructor have been invoked then p should be pointing to a diff location. why does String s3 = s2+ s1 does not invoke a copy constructor?
Please help me