1 / 46

CS31 Discussion 1H Fall18: week 9

CS31 Discussion 1H Fall18: week 9. TA: Behnam Shahbazi bshahbazi@cs.ucla.edu. Credit to former TAs: Chelsea Ju. Today’s Topic. Recap: Pointers Struct Class Project 7. Pointers. Example 1. #include < iostream > using namespace std; int main(){ int * p ; * p = 100;

cherylt
Download Presentation

CS31 Discussion 1H Fall18: week 9

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS31 Discussion 1HFall18: week 9 TA: BehnamShahbazi bshahbazi@cs.ucla.edu Credit to former TAs: Chelsea Ju

  2. Today’s Topic • Recap: Pointers • Struct • Class • Project 7

  3. Pointers • Example 1 #include <iostream> using namespace std; int main(){ int *p; *p = 100; cout << p << endl; cout << *p << endl; return 0; } Q: What is the output?

  4. Pointers • Solution 1 #include <iostream> using namespace std; int main(){ int *p; *p = 100; cout << p << endl; cout << *p << endl; return 0; } Q: What is the output? Run time error: since p is a null pointer

  5. Pointers • Example 2 #include <iostream> using namespace std; int main(){ // The value of pi const double pi = 3.141592653589793; double *p = &pi; cout << *p << endl; return 0; } Q: What is the output?

  6. Pointers • Solution 2 #include <iostream> using namespace std; int main(){ // The value of pi const double pi = 3.141592653589793; double *p = &pi; cout << *p << endl; return 0; } Q: What is the output? Compiler Error: pointer of a constant variable should be constant too

  7. Pointers and Array • An array name refers to the address of the first element • Example: • Pointer arithmetic (+, -, ++, --, +=, -=) applies to pointer values (the address), not the value of the pointed variable • ptr + 1 points to the next item of its type, not the next byte after ptr • Example • m+4 is equivalent to &m[4] int main(){ int m[8]; cout << m << endl; cout << &m[0] << endl; // m == &m[0] }

  8. Pointers and Array • Iterate through the array: • Array version: int a[5] = {0,1,2,3,4} for(intm = 0; m < 5; m++) cout << a[m]; • Pointer version: int a[5] = {0,1,2,3,4}; int *p = a; for(intm = 0; m < 5; m++) cout << *p++;

  9. Pointers and Array • Passing array as arguments • intenumerate(const string a[], intn, string target); • intenumerate(const string* a, intn, string target); • Returning a pointer • double* findFirstNegative(double a[], intn);

  10. Pointers and Array • Example 3 #include <iostream> using namespace std; intfunc(char *p){ intx=0; while(*p++ != '\0') x++; return x; } int main() { char str1[] = "CS31"; char str2[] = "Pointers are very powerful! "; cout << func(str1) << endl; cout << func(str2) << endl; } Q: What does func(char *p) do?

  11. Pointers and Array • Solution 3 #include <iostream> using namespace std; intfunc(char *p){ intx=0; while(*p++ != '\0') x++; return x; } int main() { char str1[] = "CS31"; char str2[] = "Pointers are very powerful! "; cout << func(str1) << endl; cout << func(str2) << endl; } Q: What does func(char *p) do? It counts the number of characters that p points to

  12. Pointers • Summary • To declare a pointer variable: • int *ptr; // remember to specify the type • To get the address of a variable (address-of operator): • intm; • &m • To initialize (or assign) an address to a pointer variable • int *ptr = &m; • To get the value of a variable pointed by a pointer (dereference operator): • *ptr

  13. Struct • Motivation • Allow user-defined data type that contains a collection of different data type • Syntax: structTypeName{ member1; member2; }; • Declaration & Initialization: • TypeNamevarName = {var1, var2};

  14. Struct • Motivation • Allow user-defined data type that contains a collection of different data type • Example: #include <iostream> using namespace std; struct date{ int day; int month; int year; }; int main () { date birthday = {10, 10, 1990}; date yesterday; yesterday.year = 2015; yesterday.month = 3; yesterday.day = 5; } Don’t forget the semicolon

  15. Struct • Valid Operation • Assignment • Ex: date tomorrow = {7, 3, 2015}; date examDate = tomorrow; • Function Argument • Call-by-value • Call-by-reference • Return Value • Invalid Operation • Arithmetic • Comparison • I/O

  16. Struct • Access the member variable in struct • As a normal variable: “.” operator • As a pointer variable: “->” operator • Ex: • #include <iostream> • using namespace std; • int main () { • struct date{ • int day; • int month; • int year; • }; • date birthday, *pbirthday; • birthday = {10, 10, 1990}; • pbirthday = &birthday; • cout << birthday.day << endl; • cout << pbirthday -> month << endl; • cout << (*pbirthday).year << endl; • }

  17. Struct • Example 1 #include <iostream> #include <string> using namespace std; struct employee{ int ID; double salary; string jobtitle; }; int main(){ employee emp_a; employee *emp = &emp_a; emp->ID = 100; (*emp).salary = 5000.0; emp->jobtitle = "Sales"; cout << "There is an employee:\n"; cout << "ID Number: " << emp_a.ID << endl; cout << "Salary: " << emp->salary << endl; cout << "Job Title: " << (*emp).jobtitle << endl; } Q: What is the output?

  18. Struct • Solution 1 #include <iostream> #include <string> using namespace std; struct employee{ int ID; double salary; string jobtitle; }; int main(){ employee emp_a; employee *emp = &emp_a; emp->ID = 100; (*emp).salary = 5000.0; emp->jobtitle = "Sales"; cout << "There is an employee:\n"; cout << "ID Number: " << emp_a.ID << endl; cout << "Salary: " << emp->salary << endl; cout << "Job Title: " << (*emp).jobtitle << endl; } Q: What is the output? There is an employee: ID Number: 100 Salary: 5000 Job Title: Sales

  19. Struct • Example 2 #include <iostream> #include <string> using namespace std; struct employee{ int ID; double salary; string jobtitle; }; void getRaise(employeeemp){ emp.salary *= 1.5; } int main(){ employee emp_a; employee *emp = &emp_a; emp->ID = 100; (*emp).salary = 5000.0; emp->jobtitle = "Sales"; getRaise(emp_a); cout << "There is an employee:\n"; cout << "ID Number: " << emp_a.ID << endl; cout << "Salary: " << emp->salary << endl; cout << "Job Title: " << (*emp).jobtitle << endl; } Q: What is the output?

  20. Struct • Solution 2 #include <iostream> #include <string> using namespace std; struct employee{ int ID; double salary; string jobtitle; }; void getRaise(employeeemp){ emp.salary *= 1.5; } int main(){ employee emp_a; employee *emp = &emp_a; emp->ID = 100; (*emp).salary = 5000.0; emp->jobtitle = "Sales"; getRaise(emp_a); cout << "There is an employee:\n"; cout << "ID Number: " << emp_a.ID << endl; cout << "Salary: " << emp->salary << endl; cout << "Job Title: " << (*emp).jobtitle << endl; } Q: What is the output? There is an employee: ID Number: 100 Salary: 5000 Job Title: Sales

  21. Struct • Solution 2 #include <iostream> #include <string> using namespace std; struct employee{ int ID; double salary; string jobtitle; }; void getRaise(employeeemp){ emp.salary *= 1.5; } int main(){ employee emp_a; employee *emp = &emp_a; emp->ID = 100; (*emp).salary = 5000.0; emp->jobtitle = "Sales"; getRaise(emp_a); cout << "There is an employee:\n"; cout << "ID Number: " << emp_a.ID << endl; cout << "Salary: " << emp->salary << endl; cout << "Job Title: " << (*emp).jobtitle << endl; } Q: What is the output? There is an employee: ID Number: 100 Salary: 5000 Job Title: Sales How can we change the salary?

  22. Struct • Solution 2 #include <iostream> #include <string> using namespace std; struct employee{ int ID; double salary; string jobtitle; }; void getRaise(employee&emp){ emp.salary *= 1.5; } int main(){ employee emp_a; employee *emp = &emp_a; emp->ID = 100; (*emp).salary = 5000.0; emp->jobtitle = "Sales"; getRaise(emp_a); cout << "There is an employee:\n"; cout << "ID Number: " << emp_a.ID << endl; cout << "Salary: " << emp->salary << endl; cout << "Job Title: " << (*emp).jobtitle << endl; } Q: What is the output? There is an employee: ID Number: 100 Salary: 5000 Job Title: Sales How can we change the salary?

  23. Struct • Example 3 #include <iostream> #include <string> using namespace std; struct employee{ int ID; double salary; string jobtitle; }; void getRaise(employee emp[2]){ for(inti = 0; i < 2; i++) emp[i].salary *= 1.5; } int main(){ employee emps[2] = {{100, 1000, “student”}, {101, 10000, “sales”}}; getRaise(emps); for (inti = 0; i < 2; i++){ cout << "ID Number: " << emps[i].ID << endl; cout << "Salary: " << emps[i].salary << endl; cout << "Job Title: " << emps[i].jobtitle << endl; } } Q: What is the output?

  24. Struct • Solution 3 #include <iostream> #include <string> using namespace std; struct employee{ int ID; double salary; string jobtitle; }; void getRaise(employee emp[2]){ for(inti = 0; i < 2; i++) emp[i].salary *= 1.5; } int main(){ employee emps[2] = {{100, 1000, “student”}, {101, 10000, “sales”}}; getRaise(emps); for (inti = 0; i < 2; i++){ cout << "ID Number: " << emps[i].ID << endl; cout << "Salary: " << emps[i].salary << endl; cout << "Job Title: " << emps[i].jobtitle << endl; } } Q: What is the output? ID Number: 100 Salary: 1500 Job Title: student ID Number: 101 Salary: 15000 Job Title: sales

  25. Class • Very similar to struct • Except… • All the member variables and member functions are public in struct, but private in class by default class employee { int ID; double salary; string jobtitle; void raise(){ salary *= 1.5; } }; structemployee { int ID; double salary; string jobtitle; void raise(){ salary *= 1.5; } };

  26. Public vs Private • Public: • Public members can be used directly by objects of other classes • Private: • Private members that are hidden from other classes • It is only accessible in its member function • Ex: #include <iostream> #include <string> using namespace std; class employee { private: double salary; public: int ID; string jobtitle; void setSalary(doubles){ salary = s; } }; int main(){ employee emp; emp.ID = 100; emp.jobtitle = "Student"; emp.salary = 1000.0; //not allow emp.setSalary(1000.0); //use member function to set value return 0; }

  27. Member Function • Define outside the class • Syntax • Classname::functionName() • Define inside the class • Syntax • functionName() class employee { private: double salary; public: int ID; string jobtitle; void setSalary(doubles); }; void employee::setSalary(doubles){ salary = s; } class employee { private: double salary; public: int ID; string jobtitle; void setSalary(doubles){ salary = s; } };

  28. const Function • A member function that can’t change the object • Syntax • functionName() const • Ex: class employee { private: double salary; public: int ID; string jobtitle; double getSalary(){ salary *= 1.5; return salary; } double getSalary() const{ salary *= 1.5; // not allow: complier error return salary; } };

  29. Class Constructors • A function that is automatically called when a class instance (object) is created or declared • It does NOT have any return value • Ex: #include <iostream> #include <string> using namespace std; class employee { private: double salary; public: int ID; string jobtitle; employee(){ ID = 1; jobtitle = “student”; salary = 0; } };

  30. Class Constructors • Constructors can also have arguments • Ex: #include <iostream> #include <string> using namespace std; class employee { private: double salary; public: int ID; string jobtitle; employee(inte_id, sting pos, double pay){ ID = e_id; jobtitle = pos; salary = pay; } };

  31. Class Constructors • Multiple Constructors (Overload) • Ex: class employee { private: double salary; public: int ID; string jobtitle; employee(){ ID = 1; jobtitle = “student”; salary = 0; } employee(inte_id, sting pos, double pay){ ID = e_id; jobtitle = pos; salary = pay; } }; Default Constructor Overloaded Constructor

  32. Class • Example 1: Implement the member functions #include <iostream> #include <string> using namespace std; class Pet{ public: Pet(string nm, intinitialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; intm_health; }; Pet::Pet(string nm, intinitialHealth){ // Initialize the state of the pet // Set the private variables with argument values }

  33. Class • Example 1: Implement the member functions #include <iostream> #include <string> using namespace std; class Pet{ public: Pet(string nm, intinitialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; intm_health; }; void Pet::eat(int amt){ // increase the pet’s health by the amount } void Pet::play(){ // decrease pet’s health by 1 for the energy consumed } string Pet::name() const{ // Return the pet’s name } intPet::health() const{ // Return the pet’s health } boolPet::alive() const{ // Return whether the pet is alive }

  34. Class • Example 2: Implement additional helper functions #include <iostream> #include <string> using namespace std; class Pet{ public: Pet(string nm, intinitialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; intm_health; }; void reportStatus(const Pet* p){ // print out pet status in the following format: “pet_name has health level 3” “pet_name has health level -2, so has died” }

  35. Class • Example 2: Additional helper functions. What does it do? void careFor(Pet* p, intd){ if( !p -> alive(){ cout << p-> name() << “is still dead” << endl; return; } if( d%3 == 0) cout << “Your forgot to feed “ p-> name() << endl; else{ p -> eat(1); cout << “You fed “ << p->name() << endl; } p -> play(); reportStatus(p); }

  36. Class • Example 3: Based on what we just implemented, what would be the output? #include <iostream> #include <string> using namespace std; class Pet{ public: Pet(string nm, intinitialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; intm_health; }; int main(){ Pet myPets[2] = {Pet("Fluffy", 2), Pet("Frisky", 4)}; for (inti = 0; i < 2; i++) cout << myPets[i].m_name; }

  37. Class • Solution 3: Based on what we just implemented, what would be the output? class Pet{ public: Pet(string nm, intinitialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; intm_health; }; int main(){ Pet myPets[2] = {Pet("Fluffy", 2), Pet("Frisky", 4)}; for (inti = 0; i < 2; i++) cout << myPets[i].m_name; // compiler error }

  38. Class • Solution 3: Based on what we just implemented, what would be the output? class Pet{ public: Pet(string nm, intinitialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; intm_health; }; int main(){ Pet myPets[2] = {Pet("Fluffy", 2), Pet("Frisky", 4)}; for (inti = 0; i < 2; i++) cout << myPets[i].name(); }

  39. Class • Example 4: What is the output? class Pet{ public: Pet(string nm, intinitialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; intm_health; }; int main(){ Pet *myPet = new Pet("Fluffy"); cout << myPet -> name() << endl; }

  40. Class • Solution 4: What is the output? class Pet{ public: Pet(string nm, intinitialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; intm_health; }; int main(){ Pet *myPet = new Pet("Fluffy"); // compiler error: noticed that the constructor takes two arguments cout << myPet -> name() << endl; }

  41. Class • Example 5: What if we remove “const” from alive() from both of the declaration and implementation? class Pet{ public: Pet(string nm, intinitialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; intm_health; }; void careFor(Pet* p, intd){ } void reportStatus(const Pet* p){ }

  42. Class • Solution 5: What if we remove “const” from alive() from both of the declaration and implementation? class Pet{ public: Pet(string nm, intinitialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; intm_health; }; void careFor(Pet* p, intd){ } void reportStatus(const Pet* p){ // compiler error: p is a constant variable, and can only call const functions }

  43. Dynamic Memory Allocation/Deallocation Memory Layout Text (Executable Instructions) • Static: • Size is decided at compile time by declaration • Ex: global variables • Life time – throughout the entire program execution Global / Static Variables • Stack: • Size is decided at run time • Ex: local variable, function arguments • Life time – from the function is called until the function returns Stack Heap (freestore) • Heap: • Size is decided at run time • Life time – explicitly indicated by the programmer

  44. Dynamic Memory Allocation/Deallocation • Programmer can decide the life time of a variable through dynamic memory allocation • Dynamic memory is access through pointer • Allocation: new • Syntax DataType *n = new DataType; • Deallocation: delete • Syntax delete n; // it de-allocates the object pointed by n

  45. Dynamic Memory Allocation/Deallocation • Example 7 int main(){ Pet petA = Pet("Fluffy", 2); // stack Pet *petB = new Pet("Frisky", 4); //heap // the address of these two objects are far apart cout << &petA << endl; cout << petB << endl; delete petB; // explicitly free memory }

  46. Project #7 • Due: 11:00 PM Thursday, Dec 6th, 2018 • What to submit? • zombies.cpp • Note: no report • Implementation • To complete the skeleton code: • You are allowed to add or remove any private members • You are NOT allowed to change any public members • Tips • Start Early • Start with the function marked “TODO: TRIVIAL” • Note • The code you have to write for this project is not algorithmically challenging -- the hard part is analyzing how the parts of the program work together and what the responsibilities of each class are.  It's hard only because it may be the first time you've done it.

More Related