S
sahukar praveen
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
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