| | |
Problem declaring class object array
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
•
•
Join Date: Feb 2005
Posts: 154
Reputation:
Solved Threads: 0
Hey folks - i am working on an assignment for school and would like some input if possible.
I am trying to declare a class object in the form of an array so that i can read info from file and then manipulate the data.
I need 3 seperate c++ files for this assignment. One is a header file, which contains the class definition etc. The other cpp file contains the class methods, while the third contains the main part of the program. Both the main cpp file and the methods cpp file have the header file included
Within the main.cpp file i am trying to do this:
I get a linker error with the above code. My header file is:
And my method cpp file is:
So why cant i declare my Employee employee_list[100] in the main.cpp file? Am i not referencing the Class Employee correctly? Sorry if my code is awful, i havent coded anything in 3 months and forgot half of it!
Please any answers or questions to help me would be awesome. Just point me in the right direction, throw me a link so i can learn, anything would be great.
I am trying to declare a class object in the form of an array so that i can read info from file and then manipulate the data.
I need 3 seperate c++ files for this assignment. One is a header file, which contains the class definition etc. The other cpp file contains the class methods, while the third contains the main part of the program. Both the main cpp file and the methods cpp file have the header file included
C++ Syntax (Toggle Plain Text)
#include "Employee.h"
Within the main.cpp file i am trying to do this:
C++ Syntax (Toggle Plain Text)
#include "Employee.h" #include <iostream> using namespace std; int buildEmployeeList(Employee []); int main() { int array_size = 0; // Declare Employee object array for employees Employee employee_list[100]; array_size = buildEmployeeList(employee_list); //Builds the employee array object system("PAUSE"); return 0; } int buildEmployeeList(Employee employee_list[]) { //DOES STUFF int count = 1; return count; }
I get a linker error with the above code. My header file is:
C++ Syntax (Toggle Plain Text)
#ifndef EMPLOYEE_H #define EMPLOYEE_H #include <fstream> #include <istream> using namespace std; class Employee { private: char firstName[11]; char lastName[16]; char department[16]; double salary; public: Employee(); char *getDepartment(); double getSalary(); void print(); }; #endif /* EMPLOYEE_H */
And my method cpp file is:
C++ Syntax (Toggle Plain Text)
#include "Employee.h" #include <iostream> /**************************************************************** FUNCTION: Employee:Employee() ARGUMENTS: none RETURNS: none NOTES: This is the class Employee constructor ****************************************************************/ Employee::Employee() { firstName[0] = '\0'; //Sets null char to firstName lastName[0] = '\0'; //Sets null char to lastName salary = 0; //Sets salary to 0 } /**************************************************************** FUNCTION: Employee::getDepartment() ARGUMENTS: none RETURNS: Department name NOTES: Returns the name of the department for the individual ****************************************************************/ char * Employee::getDepartment() { return department; } /**************************************************************** FUNCTION: Employee::getSalary() ARGUMENTS: none RETURNS: Salary amount NOTES: Returns the salary for an individual ****************************************************************/ double Employee::getSalary() { return salary; } /**************************************************************** FUNCTION: Employee::print() ARGUMENTS: none RETURNS: none NOTES: Prints the values of the data members ****************************************************************/ void Employee::print() { cout << "Name ---- Department ---- Salary"; } int main() { return 0; }
So why cant i declare my Employee employee_list[100] in the main.cpp file? Am i not referencing the Class Employee correctly? Sorry if my code is awful, i havent coded anything in 3 months and forgot half of it!
Please any answers or questions to help me would be awesome. Just point me in the right direction, throw me a link so i can learn, anything would be great.
>>I get a linker error with the above code
What is the error message ?
>>So why cant i declare my Employee employee_list[100] in the main.cpp file?
I thought you said you are getting a link error? link errors will not produce this error, but a compile error will. What is the exact compile error?
What is the error message ?
>>So why cant i declare my Employee employee_list[100] in the main.cpp file?
I thought you said you are getting a link error? link errors will not produce this error, but a compile error will. What is the exact compile error?
Last edited by Ancient Dragon; Jan 26th, 2008 at 8:25 pm.
Don't PM me with questions -- you might get a nasty PM in response. If you have a question then post it in one of the forums.
•
•
Join Date: Feb 2005
Posts: 154
Reputation:
Solved Threads: 0
[Linker error] undefined reference to `Employee::Employee()'
ld returned 1 exit status
Is the exact error i get. I am using dev c++.
The error is a 'linker error' so im assuming the files arent compiling correctly or seeing each other or something? What does this error really mean?
Thanks for the reply!
ld returned 1 exit status
Is the exact error i get. I am using dev c++.
The error is a 'linker error' so im assuming the files arent compiling correctly or seeing each other or something? What does this error really mean?
Thanks for the reply!
Everything compiled ok, that error message just means it could not find the class constructor. Make sure method.cpp is part of the dev-cpp project.
One error is that the project has two main() functions. you need to delete one of them.
One error is that the project has two main() functions. you need to delete one of them.
Last edited by Ancient Dragon; Jan 26th, 2008 at 9:32 pm.
Don't PM me with questions -- you might get a nasty PM in response. If you have a question then post it in one of the forums.
•
•
Join Date: Feb 2005
Posts: 154
Reputation:
Solved Threads: 0
You were right. The reason it wouldnt see the method.cpp file is that i was trying to compile the program within dev c++ but it wasnt set up as a project. Im unsure how to do this. Is it really as simple as starting a project and loading the files up into dev c++?
The way i have to compile the program is through UNIX. I created my own makefile and uploaded the 3 files, method.cpp main.cpp and employee.h onto the UNIX system, then called make , then it compiled just fine.
*** i was able to get Dev C++ to compile my program / project just fine. Thanks again for all the great help Dragon. If anything else comes up - ill post here
thanks again
The way i have to compile the program is through UNIX. I created my own makefile and uploaded the 3 files, method.cpp main.cpp and employee.h onto the UNIX system, then called make , then it compiled just fine.
*** i was able to get Dev C++ to compile my program / project just fine. Thanks again for all the great help Dragon. If anything else comes up - ill post here
thanks again Last edited by tones1986; Jan 27th, 2008 at 12:01 am. Reason: Sorted out my Dev c++ by myself :) learning folks!
•
•
Join Date: Feb 2005
Posts: 154
Reputation:
Solved Threads: 0
Another quick question. Under my class (within header file employee.h) i have firstName, lastName, department, and salary. If i am working from my main.cpp how can i access the private section of this class. I understand the only way to do this would be to be within one of the Classes methods correct? Within the main.cpp i am trying this:
I obviously get errors telling me these members are private! Duh!
(both my employee.cpp and employee.h files i posted above are unchanged from before)
I thought if i am working from an array type from the class created - it should have access aswell? no? Confused with permissions from outside of class then! Any way around this. Will keep working - has to be a logical way !Thanks in advance for suggestions or links for help with classes! (basic stuff please!)
C++ Syntax (Toggle Plain Text)
int buildEmployeeList(Employee employee_list[]) { int count = 0; ifstream inFile; inFile.open("employees1", ios::binary); if (inFile.fail()) { cout << "Unable to open employees1 file\n"; exit(1); } inFile >> employee_list[count].firstName; while (!inFile.eof()) { inFile >> employee_list[count].lastName; inFile >> employee_list[count].department; count++; inFile >> employee_list[count].firstName; } inFile.close(); return count; }
(both my employee.cpp and employee.h files i posted above are unchanged from before)
I thought if i am working from an array type from the class created - it should have access aswell? no? Confused with permissions from outside of class then! Any way around this. Will keep working - has to be a logical way !Thanks in advance for suggestions or links for help with classes! (basic stuff please!)
The whole idea of private data members is to prevent code outside the class from directly accessing them. Two reasons:
1. To hide the actual method of storing. Does it matter to main.cpp whether you use a char array based string or a string class item to hold the names? Should it matter to main.cpp if you later change how they are stored? No, not if you've constructed the class methods correctly.
2. To provide a means of validating the inputs before actually storing to the data member. Consider a date class. Would it make sense to allow a user of the class to directly set the day of month to 35?
So, you generally create public class methods that will allow the user program to pass in inputs, and the class method will then store that value to the private data member, if appropriate.
To solve your current programming problem, you probably should create get( ) and set( ) methods for each data element. Then in main read into temporary variables, and pass those values to the corresponding set( ) method.
Val
1. To hide the actual method of storing. Does it matter to main.cpp whether you use a char array based string or a string class item to hold the names? Should it matter to main.cpp if you later change how they are stored? No, not if you've constructed the class methods correctly.
2. To provide a means of validating the inputs before actually storing to the data member. Consider a date class. Would it make sense to allow a user of the class to directly set the day of month to 35?
So, you generally create public class methods that will allow the user program to pass in inputs, and the class method will then store that value to the private data member, if appropriate.
To solve your current programming problem, you probably should create get( ) and set( ) methods for each data element. Then in main read into temporary variables, and pass those values to the corresponding set( ) method.
Val
"We Americans got so tired of being thought of as dumb by the rest of the world that we went to the polls last November and removed all doubt."
~~~~~~~~~~~~~~~~~~
Looking for an exciting graduate degree? Robotics and Intelligent Autonomous Systems (RIAS) at SDSM&T See the program brochure here.
~~~~~~~~~~~~~~~~~~
Looking for an exciting graduate degree? Robotics and Intelligent Autonomous Systems (RIAS) at SDSM&T See the program brochure here.
•
•
Join Date: Feb 2005
Posts: 154
Reputation:
Solved Threads: 0
THanks for the help once again Val. I got a reply from my TA in my c++ class about my question also. With both your help i figured out a way to solve my problem. At least i thought so --- here is what i did.
This is it working - it will print out my Department, and the salary, and looking at a example print out - it all lines up with correct department and figures. BUT ... how would i access the names still? I cant do:
[code]
employee_list[i].Employee::Employee(); (the constructor contains the first name, last name, and salary
This is on my methods.cpp file. Im getting the hang of it (sort of, but would like confirmation that im on the right path - the answers just there ... i just can see it in the code...!)
Thanks once again in advance -
int buildEmployeeList(Employee employee_list[])
{
int count = 0;
//char first[16] = "\0", last[16] = "\0", depart[11] ="\0";
ifstream inFile;
inFile.open("employees1", ios::binary);
if (inFile.fail())
{
cout << "Unable to open employees1 file\n";
exit(1);
}
inFile.read((char *)&employee_list[count], sizeof(Employee));
while (!inFile.eof())
{
count++;
inFile.read((char *)&employee_list[count], sizeof(Employee));
}
inFile.close();
for (int i = 0; i < 15; i++)
cout << "Department: " << employee_list[i].getDepartment()<< "Salary: " << employee_list[i].getSalary() << endl;
return count;
}[code]
employee_list[i].Employee::Employee(); (the constructor contains the first name, last name, and salary
C++ Syntax (Toggle Plain Text)
Employee::Employee() { firstName[0] = '\0'; //Sets null char to firstName lastName[0] = '\0'; //Sets null char to lastName salary = 0; //Sets salary to 0 }
This is on my methods.cpp file. Im getting the hang of it (sort of, but would like confirmation that im on the right path - the answers just there ... i just can see it in the code...!)
Thanks once again in advance -
•
•
Join Date: Jan 2008
Posts: 3,810
Reputation:
Solved Threads: 501
You already have getDepartment and getSalary accessor functions. Write accessor functions getLastName and getFirstName. They'll be almost identical to getDepartment.
C++ Syntax (Toggle Plain Text)
class Employee { private: char firstName[11]; char lastName[16]; char department[16]; double salary; public: Employee(); char *getDepartment(); char* getLastName (); // add this function. char* getFirstName (); // add this function. double getSalary(); void print(); };
If in fact that infile.read( ) statement is working, it depends on your data file having exactly the right number of characters for each field (fname, lname, dept, oops, how's it going to read in the salary of type double?)
And you are still violating the premise that the data members are private, only to be directly accessed by class methods.
As I mentioned before, you should have methods that get and set each (or combinations of ) data element.
Here is where you build in protection. What if the user provided a first name that was 15 characters long? Copying that in full would then overwrite part of the last name, or run outside the bounds of the object's storage. Bad in either case. A better implementation would check the length of input and only store the portion that fits.
Now in main.cpp, you have:
And you are still violating the premise that the data members are private, only to be directly accessed by class methods.
As I mentioned before, you should have methods that get and set each (or combinations of ) data element.
C++ Syntax (Toggle Plain Text)
void Employee::setDepartment( char * dept ) { strcpy( department, dept ); } void Employee::setFirstname( char * fname ) { strcpy ( firstName, fname ); }
C++ Syntax (Toggle Plain Text)
void Employee::setFirstname( char * fname ) { if( strlen( fname ) < 10 ) strcpy ( firstName, fname ); else { strncpy( firstName, fname, 10 ); firstName[10] = '\0'; } }
C++ Syntax (Toggle Plain Text)
char fname[100] = ""; //big enough for any unreasonable input char lname[100] = ""; //etc. infile >> fname; //or use getline if each data item on separate line in file employeeList[n].setFirstname( fname ); //do the same read and set action for the other data elements
"We Americans got so tired of being thought of as dumb by the rest of the world that we went to the polls last November and removed all doubt."
~~~~~~~~~~~~~~~~~~
Looking for an exciting graduate degree? Robotics and Intelligent Autonomous Systems (RIAS) at SDSM&T See the program brochure here.
~~~~~~~~~~~~~~~~~~
Looking for an exciting graduate degree? Robotics and Intelligent Autonomous Systems (RIAS) at SDSM&T See the program brochure here.
![]() |
Similar Threads
- Tutorial: An introduction to Test Driven Development (Computer Science)
- Hash Table template implementation help (C++)
- Using Microsoft Excel 10.0 Libary Object -Dang .dlls (C#)
Other Threads in the C++ Forum
- Previous Thread: errors in code
- Next Thread: please help... it compiled but it does not run...
| Thread Tools | Search this Thread |
api array beginner bitmap c++ c/c++ calculator char char* class classes code coding compile compiler console conversion count database delete desktop developer directshow dll download dynamic email encryption error file forms fstream function functions game givemetehcodez google graph gui homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker linux loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive return rpg sorting string strings struct temperature template templates test text text-file tree unix url variable vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






