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

Program goes to destructor before using the object!!!

62
Hi,
I have a program with several classes which i was debugging and just found out strange thing: it creates the object in a constructor(class Employee), allocates all memory for other class objects, and then goes straight to the destructor and deallocates all memory just allocated. Only then it goes to the function using this object and gives errors because the memory has just been deallocated.
Why is it doing so????
This is the class implementation:

Expand|Select|Wrap|Line Numbers
  1. void Employee :: create(TEdit *EnterEmployeeName,
  2.                         TEdit *EnterEmployeeSurname,
  3.                         TEdit *EnterEmployeeSocialNumber,
  4.                         TEdit *EnterEmployeeSalary,
  5.                         TEdit *EnterEmployeeHouseName,
  6.                         TEdit *EnterEmployeeHouseNo,
  7.                         TEdit *EnterEmployeeStreet,
  8.                         TEdit *EnterEmployeeTown,
  9.                         TEdit *EnterEmployeePostCode,
  10.                         TEdit *EnterEmployeeCountry,
  11.                         TEdit *EnterDOBdate,
  12.                         TEdit *EnterDOBmonth,
  13.                         TEdit *EnterDOByear,
  14.                         TEdit *EnterEmploymentStartDate,
  15.                         TEdit *EnterEmploymentStartMonth,
  16.                         TEdit *EnterEmploymentStartYear,
  17.                          TEdit *EnterBankCode,
  18.                          TEdit *EnterAccountNo,
  19.                          TEdit *EnterBalance,
  20.                          TEdit *EnterBankName,
  21.                          TEdit *EnterRate,
  22.                          TEdit *EnterOverdraftLimit,
  23.                          TEdit *EnterConditions)
  24. {
  25.         //save data for the employee
  26.         FirstName = EnterEmployeeName->Text;
  27.         Surname = EnterEmployeeSurname->Text;
  28.         Salary = StrToInt(EnterEmployeeSalary->Text);
  29.         SocialNumber = StrToFloat(EnterEmployeeSocialNumber->Text);
  30.  
  31.        HomeAddress -> create(EnterEmployeeHouseName->Text,
  32.                                 StrToInt(EnterEmployeeHouseNo->Text),
  33.                                 EnterEmployeeStreet->Text,
  34.                                 EnterEmployeeTown->Text,
  35.                                 EnterEmployeePostCode->Text,
  36.                                 EnterEmployeeCountry->Text);
  37.         DOB->setDate(StrToInt(EnterDOBdate->Text),
  38.                         StrToInt(EnterDOBmonth->Text),
  39.                         StrToInt(EnterDOByear->Text));
  40.  
  41.         EmploymentStartDate->setDate(StrToInt(EnterEmploymentStartDate->Text), StrToInt(EnterEmploymentStartMonth->Text), StrToInt(EnterEmploymentStartYear->Text));
  42.  
  43.        theAccounts[0]->create(EnterBankCode->Text,
  44.                                 StrToInt(EnterAccountNo->Text),
  45.                                 StrToFloat(EnterBalance->Text),
  46.                                 EnterBankName->Text,
  47.                                 StrToFloat(EnterRate->Text),
  48.                                 StrToFloat(EnterOverdraftLimit->Text),
  49.                                 EnterConditions->Text);   
  50. }
  51.  
  52. Employee :: Employee()
  53. {
  54.         FirstName = "";
  55.         Surname = "";
  56.         SocialNumber = -1;
  57.         Salary = -1;
  58.         DOB = new clsDate();
  59.         EmploymentStartDate = new clsDate();
  60.  
  61.         HomeAddress = new Address();
  62.  
  63.         theAccounts = new Account*[3];
  64.          theAccounts[0] = new CurrentAccount();
  65. }
  66.  
  67.  
  68. Employee :: ~Employee()   /////program goes here straight from the constructor
  69. {
  70.  
  71.             delete HomeAddress;
  72.             HomeAddress = NULL;
  73.  
  74.  
  75.         delete DOB;
  76.        delete EmploymentStartDate;
  77.  
  78.         delete theAccounts[0];
  79.         delete theAccounts;
  80. }
  81.  
  82.  
  83.  
And this is the function in my Form where i call this Employee class function create(), which is preformed after the destructor...

Expand|Select|Wrap|Line Numbers
  1.  
  2. void __fastcall TForm1::CreateEmployeeButtonClick(TObject *Sender)
  3. {
  4.         theEmployeeList.addEmployee(i, Size);
  5.  
  6.         theEmployeeList.getEmployee(i)->create(EnterEmployeeName,
  7.                                               EnterEmployeeSurname,
  8.                                               EnterEmployeeSocialNumber,
  9.                                               EnterEmployeeSalary,
  10.                                               EnterHouseName,
  11.                                               EnterHouseNo,
  12.                                               EnterStreet,
  13.                                               EnterTown,
  14.                                               EnterPostCode,
  15.                                               EnterCountry,
  16.                                               EnterDOBdate,
  17.                                                 EnterDOBmonth,
  18.                                                 EnterDOByear,
  19.                                                 EnterEmploymentStartDate,
  20.                                                 EnterEmploymentStartMonth,
  21.                                                 EnterEmploymentStartYear,
  22.                                                 EnterBankCode,
  23.                                                 EnterAccountNo,
  24.                                                 EnterBalance,
  25.                                                 EnterBankName,
  26.                                                 EnterRate,
  27.                                                 EnterOverdraftLimit,
  28.                                                 EnterConditions);
  29.  
  30.  

Could someone please help...
Nov 20 '07 #1
9 1832
Could you post the code of the following function? (addEmployee)

Expand|Select|Wrap|Line Numbers
  1. theEmployeeList.addEmployee(i, Size);
  2.  
Nov 20 '07 #2
jewel87
62
Could you post the code of the following function? (addEmployee)

Expand|Select|Wrap|Line Numbers
  1. theEmployeeList.addEmployee(i, Size);
  2.  
Sure:

Expand|Select|Wrap|Line Numbers
  1.  
  2. void EmployeeList :: addEmployee(int &i, int &SIZE)
  3. {
  4.         i = SIZE;
  5.         myEmployeeList.push_back(Employee());
  6.         SIZE++;
  7.         ListSize = SIZE;
  8. }
  9.  
  10.  
Nov 20 '07 #3
RRick
463 Expert 256MB
What you are describing is the behavior between a base class and a derived class where the derived class' constructor throws an exception. In this case, the base class desctructor will be called.

The STL library uses this design where the base class handles memory allocation, and if the derived class blows up, the memory is guaranteed to be deallocated.

Since you haven't posted the class definition, does this match your situation?
Nov 20 '07 #4
Expand|Select|Wrap|Line Numbers
  1. myEmployeeList.push_back(Employee());
  2.  
Im assuming this is a list (although it could be a vector, doesnt matter).

This code creates an object in the stack, at that moment the constructor is called.

Stack objects die when the function they are created in finishes (strictly speaking they die when the scope whithin they were created in finishes), so you see the destructor being called as a result of that; i.e. when addEmployee finishes the destructor gets called.

The STL list will create a copy of your stack object.

I am assuming you dont have neither a copy constructor nor an overloaded = operator in your Employee class, so the copy STL is doing is a bad copy, since you have pointers inside your Employee class, and when you try using them the program crashes because you have already disposed those pointers in the destructor.

So to solve this problem, create a copy constructor and overload the operator= of your Employee class, just make sure to deal with pointers accordingly inside both the copy constructor and the overladed = operator.

OR

have your list use heap objects rather than stack objects and use this:
Expand|Select|Wrap|Line Numbers
  1. myEmployeeList.push_back(new Employee());
  2.  
In the latter case, make sure to free all the pointers inside the list when needed.

by the way, it is not necessary to keep a count of how many employees you have entered into the list, the function count() will give you the current list size; or is it size()? I cant remember :S
Nov 20 '07 #5
jewel87
62
Expand|Select|Wrap|Line Numbers
  1. myEmployeeList.push_back(Employee());
  2.  
Im assuming this is a list (although it could be a vector, doesnt matter).

This code creates an object in the stack, at that moment the constructor is called.

Stack objects die when the function they are created in finishes (strictly speaking they die when the scope whithin they were created in finishes), so you see the destructor being called as a result of that; i.e. when addEmployee finishes the destructor gets called.

The STL list will create a copy of your stack object.

I am assuming you dont have neither a copy constructor nor an overloaded = operator in your Employee class, so the copy STL is doing is a bad copy, since you have pointers inside your Employee class, and when you try using them the program crashes because you have already disposed those pointers in the destructor.

So to solve this problem, create a copy constructor and overload the operator= of your Employee class, just make sure to deal with pointers accordingly inside both the copy constructor and the overladed = operator.

OR

have your list use heap objects rather than stack objects and use this:
Expand|Select|Wrap|Line Numbers
  1. myEmployeeList.push_back(new Employee());
  2.  
In the latter case, make sure to free all the pointers inside the list when needed.

by the way, it is not necessary to keep a count of how many employees you have entered into the list, the function count() will give you the current list size; or is it size()? I cant remember :S
Could you please explain briefly what is a copy constructor and why will it help in this case? and what is operator =, how do i overload it? I've tried to use myEmployeeList.push_back(new Employee());
but still can't make it work... i'm so confused now and don't have much time left...
Nov 20 '07 #6
Could you please explain briefly what is a copy constructor and why will it help in this case? and what is operator =, how do i overload it? I've tried to use myEmployeeList.push_back(new Employee());
but still can't make it work... i'm so confused now and don't have much time left...
I would like to help but seems like doing so properly would require to take a look to many of your classes. I am going to try to assume a few things to help you:


Expand|Select|Wrap|Line Numbers
  1. // This is a copy constructor, notice you pass an Employee object to
  2. // the constructor, the point is making an exact copy
  3. Employee :: Employee( const Employee &employee )
  4. {
  5.         FirstName = employee.FirstName; // I assume this is a string object
  6.         Surname = employee.Surname; // I ssume this is a string object too
  7.         SocialNumber = employee.SocialNumber;
  8.         Salary = employee.Salary;
  9.  
  10.        // this is where things become icky, you now must have
  11.        // copy constructors for clsDate, Address, and Account
  12.  
  13.         DOB = new clsDate( *employee.DOB );
  14.         EmploymentStartDate = new clsDate( *employee.EmploymentStartDate );
  15.  
  16.         HomeAddress = new Address( *employee.HomeAddress );
  17.  
  18.         theAccounts = new Account*[3];
  19.          theAccounts[0] = new CurrentAccount( *employee.theAccounts[0] );
  20. }
  21. // this is the operator= it is used heavily by STLs
  22. Employee & Employee::operator=( const Employee &employee )
  23. {
  24.    if(this==&employee)
  25.       return *this;
  26.  
  27.             delete HomeAddress;
  28.             HomeAddress = NULL;
  29.  
  30.  
  31.         delete DOB;
  32.        delete EmploymentStartDate;
  33.  
  34.         delete theAccounts[0];
  35.         delete theAccounts;
  36.  
  37.         FirstName = employee.FirstName; // I assume this is a string object
  38.         Surname = employee.Surname; // I ssume this is a string object too
  39.         SocialNumber = employee.SocialNumber;
  40.         Salary = employee.Salary;
  41.  
  42.        // this is where things become icky, you now must have
  43.        // copy constructors for clsDate, Address, and Account
  44.  
  45.         DOB = new clsDate( *employee.DOB );
  46.         EmploymentStartDate = new clsDate( *employee.EmploymentStartDate );
  47.  
  48.         HomeAddress = new Address( *employee.HomeAddress );
  49.  
  50.         theAccounts = new Account*[3];
  51.          theAccounts[0] = new CurrentAccount( *employee.theAccounts[0] );
  52.    return *this;
  53. }
  54.  
As you can see now you need copy constructors for Address, clsDate and CurrentAccount.

If you are in a hurry use a list of heap objects.
list< *Employee > instead of
list< Employee >
so you would avoid all this copy constructor thing.

Regards
Nov 21 '07 #7
jewel87
62
If you are in a hurry use a list of heap objects.
list< *Employee > instead of
list< Employee >
so you would avoid all this copy constructor thing.

Regards
Thank you very much for help, i'll try to study copy constructor thing when i get a bit of time.
i'm using vectors in this case, would

vector<*Employee>

mean that i create a vector of pointers to Employee objects?
Nov 21 '07 #8
Thank you very much for help, i'll try to study copy constructor thing when i get a bit of time.
i'm using vectors in this case, would

vector<*Employee>

mean that i create a vector of pointers to Employee objects?
Correct.


As a side note, you would need to take a look into getEmployee when doing that change.
Nov 21 '07 #9
weaknessforcats
9,208 Expert Mod 8TB
void EmployeeList :: addEmployee(int &i, int &SIZE)
{
i = SIZE;
myEmployeeList.push_back(Employee()); <<<<<<
SIZE++;
ListSize = SIZE;
}
Why are you calling constructors???? There is no object.

You should have:
[code=cpp]
Employee temp;
myEmployeeList.push_back(temp);
[/quote]

The Employee() creates a temporary object that is copied to the vector.

I assume you have a proper copy constructor and aren't doing something foolish like copying pointers. If you are, when the temporary object is deleted and the destructor called, the data for the object in the vector will be deleted also. Be sure your copy constrcutor actually makes a copy of the data members.
Nov 21 '07 #10

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

Similar topics

1
by: Ram | last post by:
Hi All, I am using Object Data Source to bind data in the gridview. I have set the property AllowSorting=true. While running the application, I could sort the data only in ascending order. Is...
3
by: bxstylez | last post by:
rewrite this program (sum,average) using functions, possibly arrays? #include<stdlib.h> #include<stdio.h> main() { FILE *finpt, *foutpt;
5
by: MiM22 | last post by:
first thanks for every one who helps me... guys..I have to do program that count the value of Pi. where pi= 4( 1-(1/3)+(1/5)-(1/7)+((-1)^n/(2n+1)) I did the program but I have problems...
0
by: sajithamol | last post by:
I have a dll of a VB application which performs image manipulations. I want to build this dll file into a .cab file to embed this in the Object tag in client side. Also how to generate the classid...
1
by: fatin hhmed | last post by:
How to program RSA algorithms using python language includes the public and private key, encryption and decryption
9
by: Duggi | last post by:
I used to wonder why MS implemented C# to accept the following code using (Font f = new Font()) { // some code here. } While the same can be achieved through {
12
by: Duggi | last post by:
I used to wonder why MS implemented C# to accept the following code using (Font f = new Font()) { // some code here. } While the same can be achieved through {
0
by: progvar | last post by:
hi i am getting probleum in converting a spell check progrma made in vb 6.0 and Ms-office Word into OpenOffice Word when i made spell check program in Ms-Word and vb 6.0 it works fine but i use...
0
by: raana syeda | last post by:
Please tell me how to get the Windows Xp program file path using java as I am using java1.6.0
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...

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.