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

Slides:



Advertisements
Similar presentations
DATA STRUCTURES USING C++ Chapter 5
Advertisements

Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Inheritance Writing and using Classes effectively.
CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
LINKED QUEUES P LINKED QUEUE OBJECT Introduction Introduction again, the problem with the previous example of queues is that we are working.
Chapter 13 Pointers and Linked Lists. Nodes and Linked Lists Linked list: A sequence of nodes in which each node is linked or connected to the node preceding.
Stacks and Queues & Inheritance 2014 Spring CS32 Discussion Jungseock Joo.
Reusing Code Private or Protected inheritance. A cool class for array valarray class deals with numeric values, and it supports operation such as summing.
CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Pointer Data Type and Pointer Variables
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Object-oriented programming: C++ class A { private: …… // can be accessd by A protected: …… // can be accessed by A and // its derived classes public:
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
1 Joe Meehean.  call themselves directly  or indirectly void f(){... f();... } void g(){... h();... } void h(){... g();... }
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
CS162 - Topic #11 Lecture: Recursion –Problem solving with recursion –Work through examples to get used to the recursive process Programming Project –Any.
Rules Two Teams Questions worth 1-3 points – Entire team can confer to answer the question – Max of 2 minutes per question – You can use a computer on.
Linked Lists part 2 CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and Computer Science University.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
CS 11 C++ track: lecture 5 Today: Member initialization lists Linked lists friend functions.
Chapter 10 Inheritance and Polymorphism
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Linked Lists part 1 CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and Computer Science University.
SNPL1 Woochang Lim C+OOP = C++ C (non OOP)  C++ (non OOP+OOP)  Java (OOP) Object-Oriented Design  Object-Oriented Programming Programming with C++
Week 5 - Wednesday.  What did we talk about last time?  Recursion  Definitions: base case, recursive case  Recursive methods in Java.
LINKED LISTS Midwestern State University CMPS 1053 Dr. Ranette Halverson 1.
CS 1430: Programming in C++ 1. Class StudentList class StudentList { private: int numStudents; Student students[MAX_SIZE]; int find(const Student& s)
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
CSI 1340 Introduction to Computer Science II Chapter 6 Lists Plus.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO C++ INTERLUDE 2, CHAPT 4, 6.
CS32 Discussion Section 1B Week 2 TA: Hao Yu (Cody)
Computer Science Department Inheritance & Polymorphism.
1 Inheritance and Polymorphism Chapter Getting Started Continue the Cat Management example from previous presentation.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
CS32 Discussion Section 1B Week 10 TA: Hao Yu (Cody)
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
Chapter 16: Linked Lists.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Chapter 19: Recursion.
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Week 3 - Friday CS221.
Class A { public : Int x; A()
PRG 218 Week 5 Individual Assignment Coding: Derived Classes Please click here to buy ( (
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Recursion.
Chapter 16-2 Linked Structures
[Chapter 4; Chapter 6, pp ] CSC 143 Linked Lists [Chapter 4; Chapter 6, pp ]
Chapter 8: Class Relationships
Linked Lists.
Lists.
Classes with dynamic members
Lists CMSC 202, Version 4/02.
Topics OOP Review Inheritance Review Abstract Classes
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Presentation transcript:

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

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

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

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; }

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

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; }

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; }

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!

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; }

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; }

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

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; }

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

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!!

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;

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

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~

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!

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~

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); }

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

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) { }

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; }

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) { }

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); }

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) { }

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

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) { }

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); }

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) { }

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); }

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) { }

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); }

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

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)); }

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) { }

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

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); }