473,729 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

constructor and destructor

Hello,

This is the program that I am trying. The program executes but does not give
me a desired output.

*************** *************** *************** *
#include <iostream.h>
#include <iomanip.h>
#include <string.h>

class string{
int length;
char *str;
public:
string()
{
length = 0;
str = new char [length + 1];
strcpy(str, "\0");
}
string(const char *string)
{
cout<< "In the constructor" <<endl;
length = strlen(string);
str = new char [length + 1];
strcpy (str, string);
}
void display (void)
{
cout <<"The length is : " << length<< endl;
cout <<"The string is : " << str << endl;
}
~string()
{
cout << "In the destructor " << length << endl;
delete [] str;
}
};

void main (void)
{
string A;

A.display();
A = string("Praveen "); //explicit call
A.display();
}
*************** *************** *************** ***********

The output that I get is

The length is : 0
The string is :
In the constructor
In the destructor 7
The length is : 7
The string is : èö
In the destructor 7
Now my question is

1. why is the "destructor 7" called twice? I would expect "destructor 0" to
be called once and "destructor 7" called the next time. Am I correct?
2. I want to know is that line having a comment "explicit call" correct?
Can I make a call like this?

I would assume that my program has a bug (or is wrong) but I can not find
out. Please Help.

Thanks and Regards,
Praveen Kumar
Jul 19 '05 #1
9 8273
sahukar praveen wrote:
Hello,

This is the program that I am trying. The program executes but does not give
me a desired output.

*************** *************** *************** *
#include <iostream.h>
#include <iomanip.h>
#include <string.h>

class string{
int length;
char *str;
public:
string()
{
length = 0;
str = new char [length + 1];
strcpy(str, "\0");
}
string(const char *string)
{
cout<< "In the constructor" <<endl;
length = strlen(string);
str = new char [length + 1];
strcpy (str, string);
}
void display (void)
{
cout <<"The length is : " << length<< endl;
cout <<"The string is : " << str << endl;
}
~string()
{
cout << "In the destructor " << length << endl;
delete [] str;
}
};

void main (void)
{
string A;

A.display();
A = string("Praveen "); //explicit call
A.display();
}
*************** *************** *************** ***********

The output that I get is

The length is : 0
The string is :
In the constructor
In the destructor 7
The length is : 7
The string is : èö
In the destructor 7
Now my question is

1. why is the "destructor 7" called twice? I would expect "destructor 0" to
be called once and "destructor 7" called the next time. Am I correct?
2. I want to know is that line having a comment "explicit call" correct?
Can I make a call like this?

I would assume that my program has a bug (or is wrong) but I can not find
out. Please Help.


1. main returns int, not void
2. I believe that the first destructor 7 call is for the temporary created by
string("Praveen ")
3. You're getting garbage before the second destructor 7 because you don't have
an assignment operator.

What's happening is this:

* A is created length 0
* you display that.
* an unnamed temp is created length 7 containng "Praveen".
* You *BITWISE COPY* it to A (since you don't have an assignment operator),
meaning that A and your unnamed temp have the same value in str
* the unnamed temp is destroyed, destructor called, str is delete[] ed.
HOWEVER!!!! A.str still points to that delete[]'ed memory, and is not a valid
pointer now.
You display A, which puts out the eo garbage
You destroy A, which calls delete[] on an invalid pointe.

You need something like the following inside string:
string& operator=(const string& s)
{
if (str != s.str)
{
char *temp = new char[s.length + 1];
std::strcpy(tem p,s.str);
delete[] str;
str = temp;
length = s.length;
}
return *this;
}

Your assignments will then work properly.
Jul 19 '05 #2


red floyd wrote:

Your assignments will then work properly.


But the class still contains a flaw.
The OP needs a copy constructor too.

Rule of three:

Whenever you need one of destructor, copy constructor, assignment operator
you most always need all of them.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 19 '05 #3
Hello,

Thanks for the help. I added a function for assignment operator and a copy
constructor and obtained the correct output.

On reanalyzing the program I have some doubt. Please help me to get it
clarified.

The first destructor is called for the unnamed temp and not for the object
'A'. Am i correct? I had assumed the other way round, that the destructor is
called for object 'A'. So this tells me that if in case I need to reallocate
memory to the already created object it is user's responsibility to do so
(we are doing it in the assignment operator).

My question is 'Only destructors can be called explicitly and not the
constructors. So what is that I am doing in the line A= string("Praveen ")?
Am I not calling the constructor explicitly here?

Thanks and Regards,
Praveen Kumar

"Karl Heinz Buchegger" <kb******@gasca d.at> wrote in message
news:3F******** *******@gascad. at...


red floyd wrote:

Your assignments will then work properly.
But the class still contains a flaw.
The OP needs a copy constructor too.

Rule of three:

Whenever you need one of destructor, copy constructor, assignment

operator you most always need all of them.

--
Karl Heinz Buchegger
kb******@gascad .at

Jul 19 '05 #4


sahukar praveen wrote:

Hello,

Thanks for the help. I added a function for assignment operator and a copy
constructor and obtained the correct output.

On reanalyzing the program I have some doubt. Please help me to get it
clarified.

The first destructor is called for the unnamed temp and not for the object
'A'. Am i correct?
Yes.
I had assumed the other way round, that the destructor is
called for object 'A'.
Why?
Destructors are called when objects go out of scope.

In

A = string("Praveen "); //explicit call

* A temporary object is created, thus it's ctor is called.
* This temporary object is passed to the assignment operator of A
* Then the statement ends and thus the temporary goes out
of scope -> dtor called for the temporary.
So this tells me that if in case I need to reallocate
memory to the already created object it is user's responsibility to do so
(we are doing it in the assignment operator).
Not sure what your question is or what the above wants to say.

My question is 'Only destructors can be called explicitly and not the
constructors. So what is that I am doing in the line A= string("Praveen ")?
Am I not calling the constructor explicitly here?


No. You create an object.
Part of object creation is calling a constructor.
Get yourself into the habit of forgetting the idea of beeing able
to call a constructor (you can't). Constructors are called for you
at apropriete places - namely whenever an object comes to live and
the compiler decides which constructor it will use based on what you
specified at the point of object creation.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 19 '05 #5
sahukar praveen wrote:
Hello,

Thanks for the help. I added a function for assignment operator and a
copy constructor and obtained the correct output.

On reanalyzing the program I have some doubt. Please help me to get it
clarified.

The first destructor is called for the unnamed temp and not for the
object 'A'. Am i correct?
Yes.
I had assumed the other way round, that the destructor is called for
object 'A'.
That's the second one.
So this tells me that if in case I need to reallocate memory to the
already created object it is user's responsibility to do so (we are
doing it in the assignment operator).
Why is it the user's responsibility then? The assignment operator
handles it for him.
My question is 'Only destructors can be called explicitly and not the
constructors.
It's not really an explicit destructor call either. It's a pseudo
destructor call.
So what is that I am doing in the line A=string("Prave en")? Am I not
calling the constructor explicitly here?


No. That doesn't just call the constructor, but do everything to create
the object. That object e.g. needs memory, which the constructor
doesn't supply. Note also that you are assigning its value to A, but a
constructor doesn't return any value.
The above is the same as:

string s("Praveen");
A = s;

Just with the difference that you gave the string a name and that it
doesn't go out of scope until the code block ends.

Jul 19 '05 #6
"sahukar praveen" <sa************ @yahoo.co.in> wrote in message news:<3f******@ usenet01.boi.hp .com>...

Thanks for the help. I added a function for assignment operator and a copy
constructor and obtained the correct output.

On reanalyzing the program I have some doubt. Please help me to get it
clarified.

The first destructor is called for the unnamed temp and not for the object
'A'. Am i correct? I had assumed the other way round, that the destructor is
called for object 'A'. So this tells me that if in case I need to reallocate
memory to the already created object it is user's responsibility to do so
(we are doing it in the assignment operator).

My question is 'Only destructors can be called explicitly and not the
constructors. So what is that I am doing in the line A= string("Praveen ")?
Am I not calling the constructor explicitly here?


string A;
A = string("Praveen ");

You are constructing a temporary object of type "string", assigning it
to the existing object A (through the operator=()) and destroying the
temporary. You could say you're invoking the constructor explicitly,
but you're also invoking the assignment operator and the destructor.

--
Stephen M. Webb
Jul 19 '05 #7
Karl Heinz Buchegger wrote:

red floyd wrote:
Your assignments will then work properly.

But the class still contains a flaw.
The OP needs a copy constructor too.

Rule of three:

Whenever you need one of destructor, copy constructor, assignment operator
you most always need all of them.


Whoops! You're right. I misread the OP's code, and thought the constructor

string(const char *string)

was the copy constructor.

Sahukar, that's an exceptionally bad parameter name.
Jul 19 '05 #8

"sahukar praveen" <sa************ @yahoo.co.in> wrote in message
news:3f******@u senet01.boi.hp. com...

My question is 'Only destructors can be called explicitly and not the
constructors. So what is that I am doing in the line A= string("Praveen ")?
Am I not calling the constructor explicitly here?


I would not say "explicitly ". I would say it's called implicitly as a "side
effect" of creating the variable. I think you'd agree that if the code
looked a little different, there would be nothing explicit about the
constructor for A being called. e.g.

class A
{};
int main()
{
A a;
}
Jul 19 '05 #9

"red floyd" <no*****@here.d ude> wrote in message
news:Bz******** *********@newss vr27.news.prodi gy.com...
Karl Heinz Buchegger wrote:

red floyd wrote:
Your assignments will then work properly.

But the class still contains a flaw.
The OP needs a copy constructor too.

Rule of three:

Whenever you need one of destructor, copy constructor, assignment operator you most always need all of them.


Whoops! You're right. I misread the OP's code, and thought the

constructor
string(const char *string)

was the copy constructor.

Sahukar, that's an exceptionally bad parameter name.


Hello everybody,

Thanks for all the help. I could guess now what was wrong. I read some book
and as the information in the book was too less to get the overall picture I
had assumed somethings but in a wrong way. I got them cleared and also got
more info from this discussion.

Thanks and Regards,
Praveen Kumar
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
13224
by: Robin Forster | last post by:
I have two classes: aule_gl_window (parent class) and aule_button (sub class) I want to call the super class (parent) constructor code from the sub class constructor.
23
5178
by: Fabian Müller | last post by:
Hi all, my question is as follows: If have a class X and a class Y derived from X. Constructor of X is X(param1, param2) . Constructor of Y is Y(param1, ..., param4) .
8
1811
by: JAL | last post by:
According to MSDN2, if a managed class throws an exception in the constructor, the destructor will be called. If an exception is thrown in the constructor the object never existed so how in the world can the destructor of a object that does not exist get called! Here is the MSDN2 document: Code authored in Visual C++ and compiled with /clr will run a type's destructor for the following reasons: ....
14
3206
by: gurry | last post by:
Suppose there's a class A. There's another class called B which looks like this: class B { private: A a; public : B() { a.~A() } }
3
1776
by: sarathy | last post by:
Hi all, I have doubt regarding how objects are passed in C++. The primary problem of passing by value in C++, is that the destructor of the object passed will be called twice, thus creating possible damage to the object passed. If that is the case, why isnt the following program producing the unexpected o/p. I expect the program to print In B::printValues : 22 33 instead of
10
2971
by: Szabolcs Horvát | last post by:
Consider the attached example program: an object of type 'A' is inserted into a 'map<int, Am;'. Why does 'm;' call the copy constructor of 'A' twice in addition to a constructor call? The constructors and copy constructors in 'A' report when they are called. 'whoami' is just a unique identifier assigned to every object of type 'A'. The output of the program is: constructor 0 constructor 1
3
2083
by: yancheng.cheok | last post by:
Hello all, I try to figure out what is the sequence when we create and delete an object. After experiment on my VC++ 2003, I found that here is the sequence new-constructor-destructor-delete What I am concern is, is this sequence a C++ standard specification? Or it is compiler dependent? Thank you. Here is the code I use to perform experiment:
20
432
by: royashish | last post by:
Hi all , A question to the C++ fraternity , Why the Copy constructor ? Was suggested in Effective C++ , In Case the Object contains a Char* , a assignment operator = makes the two object point to the same address . In this case any Of the two Object is destroyed a memory leak occurs as one of the object stays on the Heap . My experiments on the same have proved otherwise .
13
3967
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
12
7204
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? class Trial { public: Trial() {
0
8925
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8763
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
9154
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6722
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
6026
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
4531
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...
1
3240
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2692
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2166
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.