473,804 Members | 2,194 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Constructor and desstructor problem

8 New Member
/*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
Nov 29 '08 #1
14 1965
svlsr2000
181 Recognized Expert New Member
In your function operator +, your returning "pass by value", this result in deletion of your object as soon as your function returns.
Nov 29 '08 #2
Sweeya
8 New Member
I understand that. But why is the destructor not being called in the second case?

i mean when i say

String S3 = S1 + S2;
Nov 29 '08 #3
Sweeya
8 New Member
I thought when you say

String S3 = S2 + S1

A copy constructor will be invoked for S3 and a destructor will be invoked for the temp obj in the operator + function
Nov 29 '08 #4
svlsr2000
181 Recognized Expert New Member
Can you check how your deleting the array once.
Nov 29 '08 #5
Sweeya
8 New Member
I am sorry but i did not understand what you said.
Nov 29 '08 #6
svlsr2000
181 Recognized Expert New Member
arrays needs to deleted using delete[]ptr. But your trying to delete using delete ptr
Nov 29 '08 #7
Sweeya
8 New Member
Hi,
I tried deleting using delete []p. But the the output is still the same
Nov 29 '08 #8
svlsr2000
181 Recognized Expert New Member
can you overload = and see once, cause i am using
string s3(s1+s2) and it works well
Nov 29 '08 #9
weaknessforcats
9,208 Recognized Expert Moderator Expert
Everyone is on the wrong track.

The constructors are fine, the destructors are fine and everything is being called at the right time. The delete [] is a red herring since you don't need that on arrays of built-in types.

What is missing is the assignment operator.

All S3 = S2 + S1 does is assign the char* returned from operator+ to S3. Then the destrcutor for temp is called and deletes the string held by S3.

Remember the Rule of the Big Three: Whenever you write a copy constructor, destructor or assignment operator, you must write all three.
Nov 29 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

11
2203
by: Amadrias | last post by:
Hi all, I am using a class to transport some data over the network. I then added the attribute to the class. My problem is that this class is part of a framework and that I do not want developers to call empty constructors. But the runtime sends me an exception when I try to serialize this class asking me to provide it with an
6
2043
by: Nafai | last post by:
Hello. I want to do something like this: class A { // It's virtual protected: float* data; int n; public: A(int a); virtual float* createData(); //...
11
1873
by: Alexander Stippler | last post by:
Hi I have already posted and discussed the following problems once, but despite really helpful hints I did not get any further with my problem (I at least learned, first to exactly consider why something does not work instead of immediately searching for work arounds) . I have the following code resulting in an ambiguity: -------------------------------------------------------- template <typename Impl> class Vector {};
45
6370
by: Ben Blank | last post by:
I'm writing a family of classes which all inherit most of their methods and code (including constructors) from a single base class. When attempting to instance one of the derived classes using parameters, I get CS1501 (no method with X arguments). Here's a simplified example which mimics the circumstances: namespace InheritError { // Random base class. public class A { protected int i;
23
7240
by: TarheelsFan | last post by:
What happens whenever you throw an exception from within a constructor? Does the object just not get instantiated? Thanks for replies.
74
16041
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the creation of this implicit default constructor, to force the creation of a struct via my constructor only? Zytan
22
3632
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float v);
13
3980
by: JD | last post by:
Hi, My associate has written a copy constructor for a class. Now I need to add an operator = to the class. Is there a way to do it without change her code (copy constructor) at all? Your help is much appreciated. JD
9
23777
by: Morten Lemvigh | last post by:
Is it possible to pass a pointer to a constructor or a class definition as argument to a function? Maybe in a way similar to passing function pointers...? The function should construct a number of objects using the given constructor. The objects should all inherit from a base class. It's not possible to pass actual objects, since it's not given on beforehand, how many should be created.
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10603
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10353
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10356
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7643
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6869
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3003
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.