CS427 Inheritance and Virtual Functions. Linked lists. 2/27. 01Replacement.cpp link! i n t GetY ( void ) { return ( y ) ; } ;

Similar documents
Lecture 10: Introduction to Inheritance

Dynamic Data Structures

CS 162, Lecture 25: Exam II Review. 30 May 2018

Week 8: Operator overloading

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Operator overloading

CS250 Final Review Questions

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Assignment of Objects

CMSC 341 Lecture 7 Lists

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Data Structures (CS301) LAB

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

An Introduction to C++

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

LECTURE 03 LINKED LIST

Written by John Bell for CS 342, Spring 2018

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University

CS250 Final Review Questions

Come and join us at WebLyceum

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

Motivation for Templates

Class and Function Templates

Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

! A data structure representing a list. ! A series of dynamically allocated nodes. ! A separate pointer (the head) points to the first

Lecture 15a Persistent Memory & Shared Pointers

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Spring 2008 Data Structures (CS301) LAB

CS201- Introduction to Programming Current Quizzes

CS250 Final Review Questions

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

Introduction to Programming Using Java (98-388)

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

CS 216 Exam 1 Fall SOLUTION

Linked Lists and other Dynamic Data Structures

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Implementing an ADT with a Class

Lecture No.04. Data Structures

Recap: Pointers. int* int& *p &i &*&* ** * * * * IFMP 18, M. Schwerhoff

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms

The University of Nottingham

CS201 Some Important Definitions

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Object-Oriented Programming. Lecture 2 Dr Piotr Cybula

Short Notes of CS201

CS24 Week 3 Lecture 1

Chapter 17: Linked Lists

CSC 210, Exam Two Section February 1999

2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked with Position Pointer (e) Doubly Linked

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

CS201 - Introduction to Programming Glossary By

Spare Matrix Formats, and The Standard Template Library

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

Module 1. C++ Classes Exercises

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

COMP 2355 Introduction to Systems Programming

Lecture 3. Lecture

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Objects and streams and files CS427: Elements of Software Engineering

G52CPP C++ Programming Lecture 20

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Object-Oriented Programming in C++

Algorithms and Data Structures

CS 11 C++ track: lecture 1

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

2 ADT Programming User-defined abstract data types

CS2210 Data Structures and Algorithms

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

CS24 Week 4 Lecture 2

COMP 250. Lecture 6. doubly linked lists. Sept. 20/21, 2017

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

lecture09: Linked Lists

Casting in C++ (intermediate level)

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Object Oriented Software Design II

AIMS Embedded Systems Programming MT 2017

Dynamic Memory Allocation

Absolute C++ Walter Savitch

Linked List using a Sentinel

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Ch. 12: Operator Overloading

CGS 2405 Advanced Programming with C++ Course Justification

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Transcription:

Inheritance and Virtual Functions. Linked lists. CS427 Lecture 12.2, 11am, 26th March 2012 In today s class 1 Recall... Inheritance 2 3 4 Limitations of arrays 5 Linked lists 6 7 8 Further linked list operations 9 The End... Recall... Inheritance Inheritance Given a class, construct from it a new class that has properties of the original class, plus some new ones. The original class is called the base class. The new one, is called the derived class. The derived class will inherit All the data members of the base class, though they can only be accessed directly if they are specified as protected by the base class (instead of private). The ordinary function members, but not constructors, destructors, or the assignment operator. The syntax for defining a derived class class Derived : public Base CS427 Inheritance and Virtual Functions. Linked lists. 1/27 CS427 Inheritance and Virtual Functions. Linked lists. 2/27 CS427 Inheritance and Virtual Functions. Linked lists. 3/27 Suppose, for example, that a base class has a method void PrintData(void). It is possible to make a derived class that also contains a (new) method call void PrintData(void). The version of PrintData(void) from the derived class will superceed the one from the base class. However, the original one does not disappear, it can still be called, but you need to use the base class name and scope resolution operator. Note: If the base and derived classes have functions with the same names, but different signatures, then the function is overloaded, not replaced. class Point protected : i n t x ; Point ( i n t X=0) x=x ; ; i n t GetX ( void ) return ( x ) ; ; void SetX ( i n t X) x=x ; ; void PrintData ( void ) ; ; void Point : : PrintData ( void ) cout << ( << x << ) \ n ; 01Replacement.cpp link! class TwoPoint : public Point private : i n t y ; TwoPoint ( i n t X=0, i n t Y=0) x=x ; y=y ; ; i n t GetY ( void ) return ( y ) ; ; void SetY ( i n t Y) y=y ; ; void PrintData ( void ) ; ; void TwoPoint : : PrintData ( void ) cout << ( << x <<, << y << ) \ n ; CS427 Inheritance and Virtual Functions. Linked lists. 4/27 CS427 Inheritance and Virtual Functions. Linked lists. 5/27 CS427 Inheritance and Virtual Functions. Linked lists. 6/27

int main ( void ) Point b ; TwoPoint d ; b. SetX ( 1 2 ) ; cout << b= ; b. PrintData ( ) ; d. SetX ( 1 ) ; d. SetY ( 2 ) ; cout << \nd= ; d. PrintData ( ) ; cout << Calling the Point version of Print Data : ; cout << d= ; d. Point : : PrintData ( ) ; return ( 0 ) ; There are other times when we need to take care which of two functions that have the same signature and belonging the base and derived class is called. In particular, consider the following code segment: Point d, b ; b = new Point ( 3 ) ; d = new TwoPoint ( 5, 6 ) ; Here b and d are both pointers to the type Point, but created using dynamically memory allocation. In particular, d in initialised as an instance of the TwoPoint class. But if we call (*d).printdata() (or, equivalently, d->printdata() it is Point::PrintData() that is called. If we want TwoPoint::PrintData() to be called, then in the definition of Point, we put before the definition of PrintData(). This is shown in 02Virtual.cpp link! As a more natural example of when a function might be required, consider the following implementation for items stored in a library. Items in the library all have, at the least, a title and a call-number. The base class item includes private members string title and int CallNumber. There are methods that print the title and call number, and a method printrecord that does both. class item protected : s t r i n g t i t l e ; i n t CallNumber ; item ( string t=, i n t n=0) t i t l e = t ; CallNumber=n ; ; void s e t T i t l e ( s t r i n g t ) t i t l e = t ; ; void setcallnumber ( i n t n ) CallNumber=n ; ; void p r i n t T i t l e ( void ) cout << t i t l e ; ; void printcallnumber ( void ) cout << CallNumber ; ; void printrecord ( void ) ; ; CS427 Inheritance and Virtual Functions. Linked lists. 7/27 CS427 Inheritance and Virtual Functions. Linked lists. 8/27 CS427 Inheritance and Virtual Functions. Linked lists. 9/27 The code for the printrecord method is: void item : : printrecord ( void ) cout << t i t l e : ; p r i n t T i t l e ( ) ; cout << ( c a l l number : ; printcallnumber ( ) ; cout << ) << endl ; Next we have a derived class specifically for books. It has a different form of call number in this case, based on the Dewey Decimal system. Each book s call number is made up of two integers. The first represents the broad category (e.g., 005=Computer programming) and the second the specific subject (e.g., 100=Software Engineering). class Book : public item private : i n t Category ; i n t Subject ; Book ( s t r i n g t =, i n t c =0, i n t s =0) t i t l e = t ; Category=c ; Subject=s ; ; void setcallnumber ( i n t c, i n t s ) Category=c ; Subject=s ; ; void printcallnumber ( void ) ; ; void Book : : printcallnumber ( void ) cout << s e t f i l l ( 0 ) << setw ( 3 ) << Category <<. << Subject ; So if we declare an object of type book, and call its method printrecord. But printrecord was inherited from the base class. That is, book::printrecord is the same as item::printrecord. So it will call item::printcallnumber. That is not what we intended. If we change the definition of item::printcallnumber in the base class to specify that it is, then the binding that is done at compile time is changed, and even though printrecord is inherited from item, we ll find that book::printrecord will call book::printcallnumber. The full example is given in 03Library.cpp link! CS427 Inheritance and Virtual Functions. Linked lists. 10/27 CS427 Inheritance and Virtual Functions. Linked lists. 11/27 CS427 Inheritance and Virtual Functions. Linked lists. 12/27

Limitations of arrays For many applications, such as your GradeBook project, it may seem natural to store the data is a dynamically sized arrays of objects. However, arrays are very rigid. For example, it is not clear how to add a new item to the middle of the list. delete an item allocate extra memory on the fly. To deal with these issues, we could use a linked list: an object that includes as one of its members a link to another object. These ideas featured in you Cs209 class. Now we ll review how they work in C++.............................................................................. There are many operations one would like to perform on a linked list: Output the items in the list Add a new item to the end of the list Add a new item to the middle of the list Delete item, etc. Linked lists A linked list is a collection of nodes, each of which has Some data element, sometimes called Cargo, A link (i.e., a pointer) to the next node in the list. If a node is implemented as a class in C++, it might also need methods to get and set the next node on the list. Here is part of a very basic example which you can find in 04OneTwoThree.cpp link! 04OneTwoThree.cpp 11 class Node friend i n t Length (Node head ) ; 13 private : i n t data ; 15 Node next ; 17 Node ( void ) next=null ; ; void setnext (Node n ) next=n ; ; 19 Node getnext ( void ) return ( next ) ; ; void setdata ( i n t d ) data=d ; ; 21 i n t getdata ( void ) return ( data ) ; ; ; Linked lists Now use this class: i n t main ( void ) 26 Node f i r s t, second, t h i r d ; 28 f i r s t. setdata ( 1 ) ; 30 f i r s t. setnext (&second ) ; second. setdata ( 2 ) ; 32 second. setnext (& third ) ; t h i r d. setdata ( 3 ) ; 34 cout << Number of items i n l i s t : 36 << Length (& f i r s t ) << endl ; system ( pause ) ; CS427 Inheritance and Virtual Functions. Linked lists. 13/27 CS427 Inheritance and Virtual Functions. Linked lists. 14/27 CS427 Inheritance and Virtual Functions. Linked lists. 15/27 The Length() function takes a linked list and computes the number of elements in the list. Length() is a simple list function, but it demonstrates several concepts which will be used in later, more complex list functions... 43 i n t Length ( Node head ) 45 Node c u r r e n t =head ; i n t count =0; 47 while ( c u r r e n t!= NULL) 49 count ++; 51 current = current >next ; 53 return ( count ) ; There are two common features of linked lists demonstrated in Length() 1 Pass The List By Passing The Head Pointer The linked list is passed in to Length() via a single head pointer. The pointer is copied from the caller into the head variable local to Length(). 2 Iterate Over The List With A Local Pointer The code to iterate over all the elements is very typical: while (current!= NULL) //... current = current->next; The key ideas of this example are 1 The local pointer, current in this case, starts by pointing to the same node as the head pointer with current = head; So when the function exits, the value of head there has not changed. 2 The while loop tests for the end of the list with (current!= NULL) This catches the empty list case 3 At the end of the while loop we have the line current = current->next; This advances the local pointer to the next node in the list. When there are no more links, this sets the pointer to NULL. CS427 Inheritance and Virtual Functions. Linked lists. 16/27 CS427 Inheritance and Virtual Functions. Linked lists. 17/27 CS427 Inheritance and Virtual Functions. Linked lists. 18/27

Now we ll develop some functions to add an items to a list. The full code is given in 05addToList.cpp link! The new functions are printlist addtostart and First, the following lines gets added to the class definition of Node 05addtoList.cpp friend i n t Length (Node head ) ; 13 friend void printlist (Node head ) ; friend void addtostart (Node &head, i n t Data ) ; 15 friend void (Node &head, i n t Data ) ; Note that pointer to the head of the list is passed by reference to the addtostart and functions. This is because they have to change the value of head in the calling function. The printlist function is the simplest: 66 void p r i n t L i s t ( Node head ) 68 Node c u r r e n t =head ; i n t count =0; 70 while ( c u r r e n t!= NULL) 72 cout << Link << count << contains 74 << current >data << endl ; current = current >next ; 76 count ++; 78 Next we ll write the addtostart function: it creates a new link at the head of the list (like a stack). It performs four operations: 1 Allocate memory for the new link, using new 2 Store the new data in the new link 3 Set the.next pointer of the new node to point to the current head of the list. 4 Change the old head pointer so that it points to the new head of the list. This last part is importance: because the function must change to value of a variable belonging to the calling function, we have to pass the address by reference. CS427 Inheritance and Virtual Functions. Linked lists. 19/27 CS427 Inheritance and Virtual Functions. Linked lists. 20/27 CS427 Inheritance and Virtual Functions. Linked lists. 21/27 The addtostart functions is defined as / 81 add a link at the start of the l i s t. Since the head of the l i s t is being changed 83 i t must be passed by reference / 85 void addtostart ( Node &headref, i n t NewData ) 87 Node newnode = new Node ; 89 newnode >setdata (NewData ) ; newnode >setnext ( headref ) ; 91 headref=newnode ; 93 Note: we could write a much shorter version of this function if we had a more sophisticated constructor. Adding a new link to the top of the list is the easiest way of adding a link. However, more often we often want to add something to the end (tail) of the list. Generally this should not change the value of the head of the list. But, because we have to allow for the case of the list being empty, we have to pass by reference. 96 / / Adding to the end of the list. If the list / / is empty, then the head gets chagned. So 98 / / we much pass by reference void ( Node &headref, 100 i n t NewData ) 102 Node newnode = new Node ; newnode >setdata (NewData ) ; 104 newnode >setnext (NULL ) ; 106 i f ( headref==null) / / if list is empty headref=newnode ; 108 else / / Find the end of the list 110 Node c u r r e n t =headref ; while ( current >next!= NULL) 112 current = current >next ; 114 current >next=newnode ; 116 Adding a new link to the top of the list is the easiest way of adding a link. However, more often we often want to add something to the end (tail) of the list. Usually this should not change the value of the head of the list. But, because we have to allow for the case of the list being empty, we have to pass by reference. CS427 Inheritance and Virtual Functions. Linked lists. 22/27 CS427 Inheritance and Virtual Functions. Linked lists. 23/27 CS427 Inheritance and Virtual Functions. Linked lists. 24/27

Further linked list operations There are many other operations that one could do on linked lists, other implementation issues, and variants. These include Using template to allow generic data types for the cargo. See 06LListTempate.cpp link! for an example. Functions to copy lists. insert a link in the middle of the list, delete a link from a list delete all items in a list, and deallocate the associated memory implement doubly-linked lists; here each link has a reference to the previous link as well as the next. The End... The final paper has 6 questions. You should attempt 4. 3 Questions on Software Engineering. Overview, and so could over any part of the course. It will, however, include the Waterfall model of the software lifecycle. Requirements; Specification; Logic and Predicate Calculus. Design (including Pseudocode, Finite State Machines, Data Flow Diagrams, ADTs, OOD), the coding and testing phases. 3 questions on C++ programming. Any topic covered in class or labs may be asked including: basic I/O and file I/O; functions: including overloading, default parameter lists, pass-by-reference, classes, including constructors and destructors; private, public, protected; operator overloading and friend functions. static variables. templates inheritance, including functions (but not) Linked Lists Full marks for FOUR questions. There is no sample paper, but many of the Revision Exercises are of exam standard. The End... The final exam will be worth 70%. The remaining 30% will come from In-class C test (%5) lab programming assignments. Software engineering assignments the Project. For details, see web-site. The end CS427 Inheritance and Virtual Functions. Linked lists. 25/27 CS427 Inheritance and Virtual Functions. Linked lists. 26/27 CS427 Inheritance and Virtual Functions. Linked lists. 27/27