473,396 Members | 1,666 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,396 software developers and data experts.

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 8253
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(temp,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******@gascad.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("Praveen")? 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******@usenet01.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.dude> wrote in message
news:Bz*****************@newssvr27.news.prodigy.co m...
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
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
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
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...
14
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
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...
10
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...
3
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 ...
20
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...
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...
12
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? ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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,...
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
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.