CIS 7124 Lecture 1

CISC 7124
Object-Oriented Programming
Payroll Sample Program in C++
employee.h

1 #ifndef EMPLOYEE_H
2 #define EMPLOYEE_H
3 
4 #include <iostream>
5 
6 #include "name.h"
7 #include "salary_info.h"
8 
9 class Employee {
10      friend std::ostream &operator <<(std::ostream &os, const Employee &employee) {
11           os << employee.empId << "\t" << employee.name << "\t" << employee.salaryInfo;
12           return os;
13      }
14 public:
15      Employee(int empId, const Name &name, const SalaryInfo &salaryInfo) : empId(empId), name(name), salaryInfo(salaryInfo) {}
16      
17      int getEmpId() {return empId;}
18      Name getName() {return name;}
19      SalaryInfo getSalaryInfo() {return salaryInfo;}
20           
21      int calcPay(int hours) {return salaryInfo.calcPay(hours);}
22           
23 private:  
24      int empId;
25      Name name;
26      SalaryInfo salaryInfo;
27 };             
28                
29 #endif    
Lines Terms Notes In Java
15 member assignment list This constructor contains an example of a situation where initialization of the data members requires a member initialization list; i.e., initialization cannot be achieve by performing assignments in the body of the constructor. As there is no default constructor for the Name class , creating a name object requires that information (last name. first name) be supplied at the time of creation. Declaring an Employee object results in the creation of that object, and since it has a data member of type Name, it must be immediately supplied with its constructor information. This cannot wait until the constructor body, as inside that body one might begin using the name data member before it's been initialized; i.e., by the time we reach the '{' of the constructor body all data members must be initialized, and thus we need to use the member initialization list to initialize the data member prior to execution of the body (the same holds true for the salaryInfo data member. Java's instance variables are references, not objects, and are initialized to null. Accessing them prior to creating objects that they reference, results in an error (which is safer than working with an uninitialized value). Java does have a situation in which initialization of certain instance variable must be performed before anything else is done iin the constructor; rather than having a member initialization list, Java requires the initialization code (which is easily recognized by the compiler) must be the first code in the constructor.
The SalaryInfo, Name and Employee classes are relatively trivial, and thus we included all function boies in the .h files eliminating the need for .cpp files.