The bellow code works fine unless I don't define destructor for the class. But it produces wrong result when I define destructor . In the destructor part I freed up the memory that was created in constructor .I think its my job to do so . But in this case doing this make my program to run with undesired output. I am very frustrated with the program. Please help me out. I can not figure out any problem with the code. All things seem to okay for me. Here I have made an array of objects of type list. Then I assigned values to the objects individually with the help of constructor. But it seems that the values are not getting initialize appropriately .But I think had not made any mistake there to initialization process. Then when I print the object data with member function display it could not produce the desire result. Although it prints the int and float data member properly. it can not print the char* data member properly.
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
class list
{
private:
char* name;
int code;
double cost;
public:
//constructor
list()
{
}
list(const char* name,int code,double cost)
{
int len=strlen(name);
this->name=new char[len+1];
strcpy(this->name,name);
this->code=code;
this->cost=cost;
}
//mem fun
void display(void)
{
cout.precision(2);
cout.setf(ios::fixed);
cout << setw(20) << this->name << setw(10) << this->code << setw (12) << cost << endl;
}
//destructor
~list()
{
delete[] this->name;
}
};
int main()
{
list item[3];
item[0]=list("Turbo C++",1001,250.95);
item[1]=list("C Primer",905,95.70);
item[2]=list("C++ Book",105,30);
cout << setw(20) << "NAME" << setw(10) << "CODE" << setw(12) << "COST" << endl;
for(int i=0;i<3;i++)
item[i].display();
return 0;
}