473,398 Members | 2,088 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Constructor and desstructor problem

8
/*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 1918
svlsr2000
181 Expert 100+
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
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
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 Expert 100+
Can you check how your deleting the array once.
Nov 29 '08 #5
Sweeya
8
I am sorry but i did not understand what you said.
Nov 29 '08 #6
svlsr2000
181 Expert 100+
arrays needs to deleted using delete[]ptr. But your trying to delete using delete ptr
Nov 29 '08 #7
Sweeya
8
Hi,
I tried deleting using delete []p. But the the output is still the same
Nov 29 '08 #8
svlsr2000
181 Expert 100+
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 Expert Mod 8TB
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
Sweeya
8
Hi,
Thanks for the reply. Overloading = has solved the problem. But i want to understand why the destructor for temp is not called when i said

String S3 = S2 + S1

instead of

S3 = S2 + S1.

I was under the impression that in the first case the copy constructor is invoked. But it does not seem so.
Nov 30 '08 #11
svlsr2000
181 Expert 100+
weaknessforcats:- Thats why i had given an hint to sweya by saying i am using s3(s1+s2),
Probably she didnt get my hint.
Nov 30 '08 #12
Sweeya
8
HI,
I have tried String S3(S2 + S1) also. That did not work.
Nov 30 '08 #13
weaknessforcats
9,208 Expert Mod 8TB
temp is deleted on my system regardless of String S3 = S1+ S2 or S3= S1+S2.

String S3 = S1 + S2 is a copy constructor call and S3 = S1 + S2 is an assignment operator call. Regalrdless, the detructor for temp is called after these calls. Be aware that the destructor call may not occur exactly after the object goes out of scope as the compiler may defer the call until later. Therefore, do not check for these destrcutor calls until the end of main().
Let's see your console output.
Nov 30 '08 #14
Sweeya
8
Hi,
I am still getting the same output and i donn see the copy constructor being invoked. While browsing through few sites, i think i found the answer to my question

The C++ standard explicitly allows compilers to eliminate temporary objects if the only way of detecting if those temporary objects exist is to track constructor and destructor calls.

A special case of this is the Return Value Optimisation (RVO), which my compiler is implementing. This optimisation basically means the compiler can avoid multiple copies if a variable within your function (eg temp within operator+()) will only be copied into a variable in the caller (eg S3 in main()).

Thanks all for helping me
Dec 1 '08 #15

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

Similar topics

11
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...
6
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
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...
45
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...
23
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
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...
22
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...
13
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...
9
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...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.