EMPLOYEE - faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/C++/ClassesNotes.docx · Web...

46
Custom Objects and Methods Object vs. Instance What is the difference between the two? Difference between an Object and an Instance Object (Human) Instance (Lupoli) What’s the difference between classes/structs? Frankly there isn’t much o code is VERY similar o the “big picture” is the same o PROGRAMMER DEFINED data types int, float, double, etc… all hold ONE variable’s value ex: Biggest Difference 1 Student Test1 Test2 Test3 average

Transcript of EMPLOYEE - faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/C++/ClassesNotes.docx · Web...

Custom Objects and MethodsObject vs. Instance

What is the difference between the two?Difference between an Object and an Instance

Object (Human) Instance (Lupoli)

What’s the difference between classes/structs? Frankly there isn’t much

o code is VERY similaro the “big picture” is the sameo PROGRAMMER DEFINED data types

int, float, double, etc… all hold ONE variable’s value ex:

Biggest Differenceo classes are more advancedo use information hiding

public much like global

private can only be accessed by member FUNCTIONS

1

StudentTest1Test2Test3

average

Introducing the Theory of Objects PROGRAMMER DEFINED data types int, double, double, etc… all hold ONE variable’s value

string Lupoli_name = “Mr. Lupoli”;string Lupoli_department = “Computer Science”;string Lupoli_title = “Lecturer”;int Lupoli_salary = -1;

we would have to create a separate variable for each, even though the variables are ALL related!!

Objectso groups related variables into ONE

table/objecto creating your OWN data

type/templateo need to only create one TEMPLATE

for each person or “instance”

2

Lupoli_name Lupoli_depart. Lupoli_title Lupoli_salaryMr. Lupoli Comp. Sci. Assist. Prof. -1

EMPLOYEEname

departmenttitle

salary

Why use Objects? C++ is based in Objects!!!

o calls them classes (reserved word) basic data types good data type to JUST hold data, very basic future game plan

o like most data we will sort our objects somehowo how will you order your objects?

Syntax for ClassesClass Code (Employee.h)

class Employee Employee{public:

string name; string department; string title; data members int salary;

};// Employee literally becomes a data type like int, char, etc…

Class setupAFTER creating your class for the “main”, add another class of whatever object you need.

Inside Employee.h, notice:1. no main()2. inside same project (3 files within the SAME project)

3

namedepartment

titlesalary

Visual Studio/Eclipse Project SetupDriver.cpp Employee.h

#include <iostream>#include <string>using namespace std;

#include "Employee.h"

void main(){

}

#ifndef EMPLOYEE_H_#define EMPLOYEE_H_

#include <iostream>#include <string>using namespace std;

class Employee{public:

string name; string department; string title; int salary;

};

#endif

Adding the header file within a Project

In a new project, create the files “Driver.cpp” and “Employee.cpp”. (Capitalization matters!!) “Driver” has the main. Copy the code above for Employee.

4

Creating an instance in the main ALL instances are created in the main!!! (For now)

o Can be created anywhere as long as it makes sense Creating an instance is when you create a variable of your new type

First Example of an instance#include <iostream>#include <string>using namespace std;

#include "Employee.h"

void main(){

Employee Eric;Eric.name = "Eric";Eric.title = "Walmart Greeter";Eric.salary = 10;Eric.department = "Doorway";

cout << Eric.name << endl;cout << Eric.title << endl;

}

5

The overall idea – The Big PictureEMPLOYEE TEMPLATE

EM002 EM001 EM003

name Mr. Hughes Mr. L Jennydepartment C.S. C.S. Admin.

title TA Assist. Prof. Site Dir.salary -100 -1 100000000

Each of these are an instance of our Employee data type that we created!!

1. Draw what 3 instances using the Employee class, of yourself, your parents, or a friends’ info (can be fake info). (DO NOT RECREATE THE CLASS!!)

Eclipse Project SetupDriver.cpp Employee.h

#include <iostream>#include <string>using namespace std;

#include "Employee.h"

int main(){

Employee Lupoli;// just created a new instanceLupoli.name = "Mr. Lupoli";

// create your own instance!!!Employee Zack;Zack.salary = 10000;Zack.name = "Zack attack";

cout << Zack.name << endl;

return 0;}

#ifndef EMPLOYEE_H_#define EMPLOYEE_H_

#include <iostream>#include <string>using namespace std;

#ifndef EMPLOYEE_H#define EMPLOYEE_H

class Employee{public:

string name; string department; string title; int salary;

// what if no public/private in front?? // by default, the data members are // set to private};

#endif

USE PUBLIC FOR NOW1. Create your OWN instance (in the main)2. Display the values in your instance3. Run the project4. Just for giggles, delete “public” in the header file. What does the error say?

6

The power of using pointers (yes, pointers) I know you hate pointers but a few of you might be asking

o so far it seems like OOP is still a lot of codingo still a lot of worko where is there a benefit?

the benefit is that the variable name is a pointer to an ENTIRE objecto passing does not require individual elementso passing an instance of an object takes along all of it’s data members

much like passing values/parameters in functions covered already using & in the parameter set makes the same difference with

concrete data types!!

Setup VisuallyWhat it looks like But it’s really Pointers

7

Passing the InstanceFunction Call

// will pass a copyvoid shortWayWithNoAccess(Employee x){

cout << "Displaying the objects values" << endl;

cout << "Name: " << x.name << endl;cout << "Salary: " << x.salary << endl;cout << "Title: " << x.title << endl;

}

shortWayWithNoAccess(Lupoli);

// will pass the original since we have access using "&"void shortWayWithAccess(Employee &x){

cout << "Displaying the objects values" << endl;

cout << "Name: " << x.name << endl;cout << "Salary: " << x.salary << endl;cout << "Title: " << x.title << endl;

// just to show we have full accessx.salary--;

}

shortWayWithAccess(Lupoli);

void longWayToDisplayEmployee(string name, int salary, string title){

cout << "Displaying the objects values" << endl;

cout << "Name: " << name << endl;cout << "Salary: " << salary << endl;cout << "Title: " << title << endl;

}

8

Compiling and naming classes There should be AT LEAST two files now in your projects

o main/drivero class/methods (not covered yet)o please look BELOW for naming scheme

remember the name of the file should match the name of the class when using an IDE (Visual Studio/Eclipse) compile with the driver file

focusedo not always the case, but enough to warn you

Example Files and SetupClass File Driver File

Employee.h Driver.cpp#include // whatever

class Employee{ member variables; // start with …

member methods;

};

#include // whatever#include “Employee.h”

int main(…){ Employee EM003; …

}

ALWAYS COMPILE FROM THE MAIN/DRIVER!!! NO EXCEPTIONS!!

9

Driver/Main()

Class 1(file)

Class 2(file)

Class 3

What’s #ifndef? Just making sure not to redefine the header #ifndef checks whether the given token “Employee” has been #defined earlier

in the file or in an included file; o if not, it includes the code between it and the closing #endif statement

Playing with #ifndefNo Issues

#include <iostream>#include <iostream>#include <string>using namespace std;

Since iostream already has #ifndef

When Issues Arise//#ifndef EMPLOYEE_H_//#define EMPLOYEE_H_

#include <iostream>#include <string>using namespace std;

class Employee{public:

string name; string department; string title; int salary;

// what if no public/private in front??};//#endif /* EMPLOYEE_H_ */#include <string>using namespace std;

#include "Employee.h"#include "Employee.h"

int main(){

Employee Lupoli;// just created a new instanceLupoli.name = "Mr. Lupoli";

In file included from ..\src\Driver.cpp:6:0:..\src\Employee.h:15:7: error: previous definition of 'class Employee' class Employee ^

10

Custom Methods within Objects just like helper methods, custom methods can be created for custom Objects the code for methods are added below the data members in the class code again like helper methods, custom methods require

o return valueo nameo parameters (if necessary)

remember, what the method needs in order to work methods are also broken down into mutators and accessors

o mutators CHANGE the value data memberso accessors just RETRIEVE (no change) data members

Object/Class with MethodsEmployee.h

#ifndef EMPLOYEE_H_#define EMPLOYEE_H_

#include <string>using namespace std;

class Employee{private:

string name; string department; string title; int salary; Empl

public: string getName( ); void setName(const string newName); string getDepartment( ); void setDepartment(const string newD ); string getTitle( ); void setTitle(const string newT); int getSalary( ); void setSalary(const int newSalary = 0); // sets a default

value string tostring( ); // this is really a Java idea, but useful

};#endif /* EMPLOYEE_H_ */

11

Employee.cpp#include <iostream>#include <string>using namespace std;

#include "Employee.h"

string Employee::getName( ) { return name; }void Employee::setName(const string newName) { name = newName; }

string Employee::getDepartment( ) { return department; }void Employee::setDepartment(const string newD ) { department = newD;}

string Employee::getTitle( ) { return title; }void Employee::setTitle(const string newT) { title = newT; }

int Employee::getSalary( ) { return salary; }void Employee::setSalary(const int newSalary) { salary = newSalary; }

string Employee::tostring( ) // this is really a Java idea, but useful{return name + "\n" + department + "\n" + title + "\n" + to_string(salary);}Why did I have to use to_string??

12

Complete Main example using the Class Employee#include <iostream>#include <string>using namespace std;

#include "Employee.h"

int main(){

Employee Heila; // just created a new instanceint nS = -1; // reused variable to enter new Salary

Heila.setName("Ms. Heila");Heila.setDepartment("HR");Heila.setSalary(11111);Heila.setTitle("Resource Manager");

// hard code way of setting her salaryHeila.setSalary(10);

// user input way of setting her salary (Scenario #1)cout << "Please place in Heila's new salary" << endl;cin >> nS;Heila.setSalary(nS);

cout << "Heila's new salary is: " << Heila.getSalary() << endl;

return 0;}

1. In the main(), create another instance of your TA!!! I want you to get user input for your TA’s values.

2. Display those values at the end of the main().3. WHY DOESN’T NAME, DEPARTMENT, and SALARY need to be

declared, OR an INSTANCE in front??4. Identify the return type of the method getSalary()?

13

Indentify the following about the above object’s methodsname of method return type parameter (if any) what does it do?getName() string

Access modifiers (public and private) encapsulation is the concept of determining what items of data should be

EASILY accessible or HARD to get too access from the main/driver

there are two types (actually more, but later) public

o methods and variables that CAN be accessed by the class AND main() private

o methods and variables that CAN NOT be access by the main, but CAN BE from INSIDE the class

Strategy, what would YOU want people to be able to see? It is safer to be private

o Then use “getter/setter” functions to access Super simple to create

14

Source vs. Driver access to private members if the member variables are PRIVATE, only the source has access this is used to hide information, not totally, but at least makes it harder

Information Hiding using Public/PrivateHeader

#ifndef PERSON_H_#define PERSON_H_

#include <string>using namespace std;

class Person{private:

string fname;string lname;int age;char gender;float weight;float height;

public:int getAge() const;void setAge(int age);const string& getFname() const;void setFname(const string& fname);char getGender() const;void setGender(char gender);float getHeight() const;void setHeight(float height);const string& getLname() const;void setLname(const string& lname);float getWeight() const;void setWeight(float weight);

int memberShouldNotHere;// custom functions (prototype)Person fileValues();

};

#endif /* PERSON_H_ */

15

Source

Driver

BUT!!! Finish the code, and this is what you will get:

16

Notice it STILL may allow to select it,

BUT…

Bank Account Automobile

Long int/string account_numberDouble interest rateDouble balancestring account_typeLong int routing_numberInt/string SSNDATE Open datestring bank_nameBoolean current

Mileage (int)Vin# (string)Model (string)Make (string)Year (int)Brake_type (string) ABS, standard…Drive_tran (Boolean) automatic,..Plate # (string)Horsepower (int)Max_speed (string/Int)NumOfWindowsNumOfDoors

Look at all data members, as a group, decide on which are public or private

Notice: From here out all data members will be PRIVATE in my notes

17

Encapsulation – Class setup We are using a method to change the values, NOT changing them directly!! Need a method to return the actual value

What the class code should look likeEmployee.h

#ifndef EMPLOYEE_H_#define EMPLOYEE_H_

class Employee{private:

string name;string department;string title;int salary;

public:// mutatorsvoid setName(const string newName); // set namevoid setDepartment(const string newDP); // sets departmentvoid setTitle(const string newTitle); // sets titlevoid setSalary(const int newSalary); // sets salary

// accessorsstring getName( ); // retrieves salarystring getDepartment( ); // retrieves departmentstring getTitle( ); // retrieves titleint getSalary( ); // retrieves salary

// tostringstring tostring( );

}#endif /* EMPLOYEE_H_ */

18

Notice not using pointers here, but could!!!

Employee.cpp (Partial)// set namevoid Employee::setName(const string newName) { name = newName; }

// sets departmentvoid Employee::setDepartment(const string newDP){ department = newDP;}// sets titlevoid Employee::setTitle(const string newTitle) { title = newTitle; }// sets salaryvoid Employee::setSalary(const int newSalary) { salary = newSalary; }// retrieves salarystring Employee::getName( ) { return name; }// retrieves departmentstring Employee::getDepartment( ) { return department; }// retrieves titlestring Employee::getTitle( ) { return title; }// retrieves salaryint Employee::getSalary( ) { return salary; }// tostringstring tostring( ){ return name + “\n” + department + “\n” + title + “\n” + to_string(salary);}

19

Encapsulation – Instance (main) setup remember

o an instance is created in the main/drivero instance values are set/returned in the driver

In the main()…

Employee EM001;EM001.setName(“Mr. Lupoli”);EM001.setDepartment(“Computer Science”);EM001.setTitle(“Lecturer”);EM001.setSalary(-1);cout << EM001.toString(); // uses tostring method in class

// what do you think the LAST line will print?

1. Delete all instances created in the main().2. Create 2 instances using the Employee class, of yourself, and a friends’ info

(can be fake info) using the new structure: (DO NOT RECREATE THE CLASS!!)

3. Display instance values to confirm 4. Compile and Run

What can you put into a method?? Anything you have already learned!!

o Loopso Arrayso If-elseo Variableso Etc…

20

See how a method works (Mechanics) code literally makes a jump in the program function then returns back to where it was called

Method MechanicsEmployee SOURCE Employee Driver

// mutatorsvoid Employee::setName(const string newName){

name = newName; } // set name

include //whatever

int main(){

Employee EM001; EM001.setName("Mr. L”);

}

Putting the Three File system together the code is usually not the issue for students the includes can be an issue

o making one mistake there can ruin otherwise great codeo driver and source ARE the same setup!

using Visual Studio (YouTube)

21

A next ???(class) Method method to help get info to create a new instance will ask for info to complete each member value uses member functions called from the main() watch for when you are grabbing strings and ints in the same function

NextEmployee() ExampleSource

#include <iostream>#include <string>using namespace std;

#include "Employee.h"

...// description: This function gathers all code for inputting a new instance's values// you may need to include <iostream> since we are using cin and cout.// input: None// output: While there is not a return, the instance calling this will be updatedvoid Employee::nextEmployee(){

string temp; // temperary value that will be used for all string inputint value; // temperary value that will be used for all integer inputcout << "Entering new values for this instance" << endl;cout << "Please enter this instance's of Employee's name: " << endl;cin >> temp;setName(temp);cout << "Please enter this instance's of Employee's department: " << endl;cin >> temp;setDepartment(temp);cout << "Please enter this instance's of Employee's title: " << endl;getline(cin, temp);setTitle(temp);

cin.clear();cin.ignore(10000,'\n'); // if not placed here, the input for an integer is

bypassed

cout << "Please enter this instance's of Employee's salary: " << endl;cin >> value;setSalary(value);cout << "Thank you. Values entered." << endl;

}

22

CallEmployee Megan;// proving for now Megan's department is garbagecout << Megan.getDepartment() << endl;Megan.nextEmployee();// proving for now Megan's department is legit after nextEmployee

functioncout << Megan.getDepartment() << endl;

Running

Arrays data members within Classes (issues!!) this is an issue in C++ remember that a Class is a template, values are NOT set this issue is we can create the pointer portion of the array, but not the size

The problems with arrays within classesWhat I wanted What it allowed me

what also complicates this is that the member array is PRIVATEo so I can't set the length in the driver/main()

23

The problems with arrays within classesWhat I wanted

What it allowed mevoid Person::setEmerContactSize(const int size){

emerContact = new string[size];}

#include "Person.h"

int main(){

Person Jeffrey;

Jeffrey.setEmerContactSize(3);

...

24

Array of Classes NOT THE SAME AS CLASSES WITH ARRAYS!!!! An array of classes are exactly the same as an array of structs just again with

variables and functions We can use an array of classes just like an array!! We can use for loops to access a huge amount of data since the classes are

identified by indices!!!

Student * CS1044 = new Student[100]; // Student IS NOW A DATA TYPE!!// int x[100];

0 1 2 3 4 5 6 7 8Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2Test3 Test3 Test3 Test3 Test3 Test3 Test3 Test3 Test3

CS1044[0].Test1 = 70; // student #0 got a 70 on Test1CS1044[1].Test1 = 40; // student #1 got a 40 on Test1CS1044[2].Test1 = 90; // student #2 got a 90 on Test1CS1044[4].getTestAverage( ); // will display the test average for student #4delete [] CS1044;CS1044 = NULL;

25

0 1 2 3 4 5 6 7 870 40 90 Test1 100 Test1 Test1 Test1 Test1

Test2 Test2 Test2 Test2 100 Test2 Test2 Test2 Test2Test3 Test3 Test3 Test3 100 Test3 Test3 Test3 Test3

for (int i = 0; i < 25; i++){ Period1[i].getTestAverage( ); } // will display test averages for the entire Period1 class

Displaying an ENTIRE array of classesREMEMBER!! It’s just an array, with a CLASS inside!! Still acts like an array!!

So, how did we display a NORMAL array of 100 elements??

for (int i = 0; i < 100; i++) // this is how we did this with a NORMAL array{

cout << array[i] << endl;}

NOW WITH OUR STRUCTS, WE NEED TO DISPLAY EACH MEMBER VARIABLE!!

code WITHOUT overloading cout <<

code WITH overloading cout <<

for (int i = 0; i < 100; i++){

cout << CS1044[i].Test1 << endl;cout << CS1044[i].Test2 << endl;cout << CS1044[i].Test3 << endl;

}

for (int i = 0; i < 100; i++){

cout << CS1044 [i] << endl;}// need to create OVERLOAD cout for INDEXCARD

26

FYI Section

Review of Parameters what does a method need for it to work?

o Example, finding the hypotenuse of a right triangle needs: side A length side B length

need to pass both values into the function if you wish to find the hypotenuse the parameter list can be reused over and over again with DIFFERENT values

o called aliases

Review of Hypotenuse and trianglesc2 = a2 + b2 (c being the hypotenuse)

62 + 82 = c2

36 + 64 = c2

100 = c2

c = √100c = 10

27

Hypotenuse function using parametersThe function

double Triangle::getHypotenuse(int a, int b){

return sqrt(a* a + b * b);}

What datatype will this function return?What variables are parameters?

The call to that function

Triangle example;

double answer1 = example.getHypotenuse(8,6);double answer2 = example.getHypotenuse(9, 12);double answer3 = example.getHypotenuse(16,30);

// Please notice that “a” and “b” are reused and given new values EACH time!!

Receiving parameters from the user

// user input valuescout << “give 2 values for a right triangle” << endl;int x;int y;cin >> x >> y;

double answer4 = example.getHypotenuse(x,y);// Please notice that “a” and “b” are reused and given new values EVEN HERE!!

Why will x and y work??

28

Methods with Parameters in Employee fitting an example of a custom function with multiple parameters and an

Employee remember that methods, can access values from the instance (member

variables) not just from parameters

Member functions with parameters

void Employee::printPayCheck(double hours, double taxPercentage){

cout << "----------- You should receive in your check --------” << endl;double pay = hours * wage * (1.00-(taxPercentage/100));cout << "" + fmt.format(pay));

}// wage was a member from the class// hours and taxPercentage were values passed in as parameters

Employee e("John Adams", "Boston, MA", 2, 2400.00);e.setWage(12.50);e.printPayCheck(35, 33);

29

Alias values given temporary name HAVE TO SHARE THE same data

type items and functions asks for:

o how many? (parameters)o what type are each?

THEY DO NOT ASK FOR A NAME!!!

double getHypotenuse(int a, int b){

return Math.sqrt(a* a + b * b);}

// how many parameters does the function need to work?// what TYPES does it need

void function(int x, double y, char z){ …}

// how many parameters does the function need to work?// what TYPES does it need

char function (int x, int y, double z){ …}

// how many parameters does the function need to work?// what TYPES does it need

void function (double x, double y, char z){ …}

// how many parameters does the function need to work?// what TYPES does it need

double function (int x, double y, char []z){ …}

// how many parameters does the function need to work?// what TYPES does it need

30

What is overloading?? methods that share the exact method name, but different parameters, and

possibility different NUMBER of parameters

void getMethod(int score) // Method #1{cout << “Method #1” );cout << score );}

void getMethod (char grade) // Method #2{cout << “Method #2” );cout << grade );}

void getMethod (double average) // Method #3{cout << “Method #3” );cout << average );}

int main( ){Example.getMethod (98); What method # will be called??Example.getMethod (12.3); What method # will be called??Example.getMethod (‘F’); What method # will be called??

Sources(ifndef)http://www.cprogramming.com/reference/preprocessor/ifndef.html

31