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
46
Embed
EMPLOYEE - faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/C++/ClassesNotes.docx · Web viewcalls them classes (reserved word) basic data types. good data type to JUST hold
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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 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;
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){
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
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
// 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
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
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
...// 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];
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;
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?
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??