Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS32 Discussion Section 1B Week 5 TA: Hao Yu (Cody)

Similar presentations


Presentation on theme: "CS32 Discussion Section 1B Week 5 TA: Hao Yu (Cody)"— Presentation transcript:

1 CS32 Discussion Section 1B Week 5 TA: Hao Yu (Cody)

2 Reminder & Agenda Inheritance Recursion Homework 3 due next Tuesday 9:00 p.m.

3 Inheritance The process of deriving a new class using another class as a base Why we need inheritance? Example Dog Age Speak Cat Age Speak Monkey Age Speak doMath

4 Inheritance Dog Age Speak Cat Age Speak Monkey Age Speak doMath class Dog { public: Dog(); ~Dog(); void setAge(int a) { m_age = m; } int getAge() { return m_age; } void speak() const { cout << "woof!\n";} private: int m_age; } class Monkey { public: Monkey(int n); ~Monkey(); …… void speak() const { cout << "Ooh ah!\n";} int doMath(int a) { return num + a; } private: int m_age; int m_num; } class Cat { public: Cat(); ~Cat(); void setAge(int a) { m_age = m; } int getAge() { return m_age; } void speak() const { cout << “meow~\n";} private: int m_age; }

5 Inheritance Dog Age Speak Cat Age Speak Monkey Age Speak doMath Animal Age Speak class Animal { public: Animal(); ~Animal(); void setAge(int a) { m_age = a; } int getAge() { return m_age; } void speak() const { count << “N/A\n”; } private: int m_age; } Base class

6 Inheritance Dog Age Speak Animal Age Speak Base class class Dog : public Animal { public: Dog(); ~Dog(); } Derived class class Animal { public: Animal(); ~Animal(); void setAge(int a) { m_age = a; } int getAge() { return m_age; } void speak() const { count << “N/A\n”; } private: int m_age; }

7 Inheritance Monkey Age Speak doMath Animal Age Speak Base class class Monkey : public Animal { public: Monkey(int n); ~Monkey(); int doMath(int a) { return m_num + a; } } Derived class class Animal { public: Animal(); ~Animal(); void setAge(int a) { m_age = a; } int getAge() { return m_age; } void speak() const { count << “N/A\n”; } private: int m_age; }

8 What Can You See? Public functions: setAge() getAge() speak() Private members: m_age Animal Public functions: setAge() getAge() speak() doMath() Private members: n_num Monkey Derived class: All member functions except Overloaded assignment operator Constructor/Deconstrcutor All non-private member variables Base class: Only see yourself YOU KNOW NOTHING about the derived classes!

9 Exercise Public functions: setAge() getAge() speak() Private members: m_age Animal Public functions: setAge() getAge() speak() doMath() Private members: m_num Monkey Animal animal; Monkey monkey; Is monkey.getAge() valid? Is animal.doMath(3) valid? Can we add a new function in Monkey as follows? void addAge(int a) { m_age += a; }

10 The Order of Constructors What happens when we construct a Monkey? 1.Construct the base class (Animal) 2.Construct the member variable of Monkey 3.Construct the Monkey Monkey Animal m_age 0 m_num n Monkey::Monkey(int n) { m_num = n; } Implementations Monkey::Monkey(int n, int age) : m_age(age) { m_num = n; } Monkey::Monkey(int n, int age) { m_age(age) m_num = n; }

11 The Order of Deconstructors Reverse the order! Dog() Cat() Monkey(5) Cat() Monkey(7) ~Monkey() ~Cat() ~Monkey() ~Cat() ~Dog()

12 Overriding Member Functions Animals can speak! But… We want every animal to speak! Override member function speak Animal::speak() const { cout << "N/A" << endl; } Monkey::speak() const { cout << "Ooh ah!" << endl; } Dog::speak() const { cout << “Woof!" << endl; } Cat::speak() const { cout << “Meow~" << endl; }

13 Overriding vs. Overloading Overriding Same function name, arguments, return type (everything) Define again in the derived classes Overloading Same function name Different return type and/or arguments

14 Exercise What’s the output of the following program? int main() { Animal a1; a1.speak(); Dog d1; d1.speak(); Animal *a2 = new Cat; a2->speak(); } Output: N/A Woof! N/A Polymorphism Program doesn’t know which speak function should be called!!

15 Polymorphism Late / dynamic binding The actual type is decided in runtime Polymorphism “Animal *” can take multiple forms Animal *animals[3]; animals[0] = new Dog; animals[1] = new Cat; animals[2] = new Monkey;

16 Virtual Functions class Animal { public: Animal(); virtual ~Animal(); void setAge(int a) { m_age = a; } int getAge() { return m_age; } virtual void speak() const { count << “N/A\n”; } private: int m_age; } Base class class Monkey : public Animal { public: Monkey(int n); virtual ~Monkey(); virtual void speak() const { count << “Ooh ah!\n”; } int doMath(int a) { return m_num + a; } } Derived class

17 Exercise What’s the output of the following program? int main() { Animal a1; a1.speak(); Dog d1; d1.speak(); Animal *a2 = new Cat; a2->speak(); } Output: N/A Woof! Meow~

18 Pure Virtual Functions In practice, animal has no “default” speak! Which animal speaks “N/A”?? Make speak as a pure virtual function Every derived class has to implement it class Animal { public: Animal(); virtual ~Animal(); void setAge(int a) { m_age = a; } int getAge() { return m_age; } virtual void speak() const = 0; private: int m_age; } A class has at least one pure virtual function called abstract base class You cannot new an abstract base class type object!

19 Exercise What’s the output of the following program? void callSpeak1(Animal a) { a.speak(); } void callSpeak2(Animal &a) { a.speak(); } void callSpeak3(Animal *a) { a->speak(); } int main() { Dog d; Animal *c = new Cat; callSpeak1(d); callSpeak2(d); callSpeak3(&d); callSpeak1(*c); callSpeak2(*c); callSpeak3(c); } N/A Woof! N/A Meow~

20 Recursion The function refers to itself Leap of faith Believe the function is doing the right thing Make the base case return the right value int factorial(int n) { int temp = 1; for (int i = 1; i <= n; i++) temp *= i; return temp; } int factorial(int n) { if (n == 1) return 1; return n * factorial(n - 1); }

21 How to Write Recursive Functions Steps 1.Find the base cases What are the corner cases? e.g. empty array What’s the terminal condition? e.g. n=0, length=1 2.Decompose the problem What’s the small problem you solve in one iteration? 3.Finish the small problem Pseudo code Notice Theoretically any recursion and iterative implementation can be transformed to each other Iterative implementation has better performance function(arguments) Handle base cases Get the current data Call itself with same of different arguments Combine results Return

22 Exercise 1: Average Function spec Base case? n = 1: The average of one number is just itself Subproblem? average(arr[0~(n-2)]) {arr[n-1] + (n-1) x average(arr[0~(n-2)])} / n // assume n > 0 double average(const double arr[], int n) { }

23 Exercise 1: Average // assume n > 0 double average(const double arr[], int n) { if (n == 1) return arr[0]; double subAvg = average(arr, n-1); return (arr[n-1] + (n-1) * subAvg) / n; }

24 Exercise 2: Print Elements Function spec Base case? n = 0: Nothing to print Subproblem? printArrInOrder(arr + 1, n - 1) Print arr[0] and call printArrInOrder(arr + 1, n - 1) void printArrInOrder(int arr[], int n) { }

25 Exercise 2: Print Elements void printArrInOrder(int arr[], int n) { if (n == 0) return ; cout << arr[0] << endl; printArrInOrder(arr + 1, n - 1); } How about reverse order? void printArrRevOrder(int arr[], int n) { if (n == 0) return ; cout << arr[n - 1] << endl; printArrInOrder(arr, n - 1); }

26 Exercise 3: Summing Digits Function spec Base case? n < 10: The sum of a single digit is just itself Subproblem? sumOfDigits(n / 10) (n mod 10) + sumOfDigits(n / 10) // assume n >= 0 int sumOfDigits(const int n) { }

27 Exercise 3: Summing Digits // assume n >= 0 int sumOfDigits(const int n) { if (n < 10) return n; return (n % 10) + sumOfDigits(n / 10); }

28 Exercise 4: Exponential Function spec Base case? b = 0: a 0 = 1 Subproblem? exp(a, b - 1) a * exp(a, b - 1) // assume b >= 0 int exp(const int a, const int b) { }

29 Exercise 4: Exponential // assume b >= 0 int exp(const int a, const int b) { if (b == 0) return 1; return a * exp(a, b - 1); } Can you make it better (faster)? int exp(const int a, const int b) { if (b == 0) return 1; else if ((b % 2) == 0) { int temp = exp(a, b / 2); return temp * temp; } return a * exp(a, b - 1); }

30 Exercise 5: Remove Duplication Function spec Base case? curNode->next == null: End of the linked list Subproblem? removeDuplicates(curNode->next) if (duplicate) delete curNode; removeDuplicates(curNode->next) // assume curNode != head and doubly linked list void removeDuplicates(Node *curNode) { }

31 Exercise 5: Remove Duplication // assume curNode != head and doubly linked list void removeDuplicates(Node *curNode) { if(curNode->next == null) return ; else if(curNode->value == curNode->next->value) { curNode->prev->next = curNode->next; curNode->next->prev = curNode->prev; Node *temp = curNode->next; delete curNode; return removeDuplicates(temp); } return removeDuplicates(curNode->next); }

32 Exercise 6: Greatest Common Divisor Function spec Base case? a % b = 0: b is the GCD Subproblem? gcd(b, a % b) // assume a, b >= 1 int gcd(int a, int b) { }

33 Exercise 6: Greatest Common Divisor // assume a, b >= 1 int gcd(int a, int b) { int r = a % b; if (r == 0) return b; else return gcd(b, r); }

34 Exercise 7: Palindrome Function spec Base case? String length <= 1: Must be palindrome Subproblem? palindrome(1, last - 1) bool palindrome(const string &s) { }

35 Exercise 7: Palindrome bool palindrome(const string &s) { if (s.size() <= 1) return true; if (s[0] != s[s.size() - 1]) return false; return palindrome(s.substr(1, s.size() - 2)); }

36 Exercise 8: Parade Organization Description: Organize the parade consisting of bands and floats. Any band cannot be placed right after another. How many ways can you organize a parade of size n? Function spec Base case? Subproblem? int solveParade(int n) { }

37 Exercise 8: Parade Organization bf bff bf f bf f bfbfbf f n=1 n=2 n=3 n=4 A band can only be connected after a float #b(4) = #f(3) A float can be connected after both #f(4) = #f(3) + #b(3) Subproblem? #f(n-1) + {#f(n-1) + #b(n-1)} = {#f(n-2) + #b(n-2)} + solveParade(n-1) = solveParade(n-2) + solveParade(n-1) Base cases? n=1: 2 n=2: 3

38 Exercise 8: Parade Organization int solveParade(int n) { if (n == 1) return 2; if (n == 2) return 3; return solveParade(n-1) + solveParade(n-2); }


Download ppt "CS32 Discussion Section 1B Week 5 TA: Hao Yu (Cody)"

Similar presentations


Ads by Google