BEgInSlIdE OOP-1 Simple Containers in C++ uList: simple container class uIterators uMemory Allocation Responsibility uMixed type collections uAbstract.

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

DATA STRUCTURES USING C++ Chapter 5
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
M180: Data Structures & Algorithms in Java
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
1 Class Constructors a class constructor is a member function whose purpose is to initialize the private data members of a class object the name of a constructor.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Data Structures Using C++ 2E
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Memory Management CS Chakrabarti Variable storage thus far  Never used global variables  All variables allocated inside functions, passed.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Programming Languages and Paradigms Object-Oriented Programming.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
Pointers Pointer a data type stores a memory address points to whatever the memory location contains A pointer is a variable that can store a memory address.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Linked lists. Data structures to store a collection of items Data structures to store a collection of items are commonly used Typical operations on such.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
1 CS 132 Spring 2008 Chapter 5 Linked Lists p
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Yan Shi CS/SE 2630 Lecture Notes
Pointers and Dynamic Arrays
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 16-2 Linked Structures
CS212: Object Oriented Analysis and Design
Linked Lists.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
Presentation transcript:

bEgInSlIdE OOP-1 Simple Containers in C++ uList: simple container class uIterators uMemory Allocation Responsibility uMixed type collections uAbstract Container Classes uNon-Intrusive lists

bEgInSlIdE OOP-2 Iterators i i const N = 100; double a[N]; for (int i = 0; i < N; i++) {... // Process a[i]... } const N = 100; double a[N]; for (int i = 0; i < N; i++) {... // Process a[i]... } uAn iterator is used for iterating (traversing/scanning) over all members of a container. Required operations are: lDeclare lInitialize lGet element lIncrement (Decrement?) lCheck if last uArray iterators are just integers...

bEgInSlIdE OOP-3 List Container Class void driver(void) { List mid_east; mid_east.insert(new Leader("Assad", "Syria")); mid_east.insert(new Leader("Peres", "Israel")); mid_east.insert(new Leader("Hussein", "Jordan")); List::Iterator i(mid_east); for (; i; ((Leader *)i.next())->print()) ; mid_east.insert(new Leader("Mubarak", "Egypt")); for (i.reset(); i; ((Leader *)i.next())->print()) ; } void driver(void) { List mid_east; mid_east.insert(new Leader("Assad", "Syria")); mid_east.insert(new Leader("Peres", "Israel")); mid_east.insert(new Leader("Hussein", "Jordan")); List::Iterator i(mid_east); for (; i; ((Leader *)i.next())->print()) ; mid_east.insert(new Leader("Mubarak", "Egypt")); for (i.reset(); i; ((Leader *)i.next())->print()) ; } uGeneralization: array with integer iterators - into a generalized list container with typical list operations, which could be used to store objects of any type. uWe would like our container class used as follows:

bEgInSlIdE OOP-4 Memory Allocation Responsibilities uWhat’s stored in the container? lobjects Container must make a copy of all stored objects and be responsible for allocating and deallocating them. lpointers Who allocates memory for the stored objects? User - Automatic objects cannot be stored. Container - Stored objects are created using copy constructor. Who deallocates the objects? User - The user code must keep record of all objects stored in the container, so that it could erase them. Container - Usually the preferred way. Node::Node(const String& s) : str(s){} Node::Node(const String* s) : sptr(s){} Node::Node(const String& s) : sptr(new String(s)){}

bEgInSlIdE OOP-5 Memory Allocation and Deallocation Responsibilities with Our Interface void driver(void) { List mid_east; mid_east.insert(new Leader("Assad", "Syria")); mid_east.insert(new Leader("Peres", "Israel")); mid_east.insert(new Leader("Hussein", "Jordan")); List::Iterator i(mid_east); for (; i; ((Leader *)i.next())->print()) ; mid_east.insert(new Leader("Mubarak", "Egypt")); for (i.reset(); i; ((Leader *)i.next())->print()) ; } void driver(void) { List mid_east; mid_east.insert(new Leader("Assad", "Syria")); mid_east.insert(new Leader("Peres", "Israel")); mid_east.insert(new Leader("Hussein", "Jordan")); List::Iterator i(mid_east); for (; i; ((Leader *)i.next())->print()) ; mid_east.insert(new Leader("Mubarak", "Egypt")); for (i.reset(); i; ((Leader *)i.next())->print()) ; } Allocation in user code The container stores pointers to objects allocated in user code. Allocation in user code The container stores pointers to objects allocated in user code. Deallocation in container code The List destructor mid_east.~List executed when driver() returns must delete all the inserted items Deallocation in container code The List destructor mid_east.~List executed when driver() returns must delete all the inserted items

bEgInSlIdE OOP-6 The List Interface class List { public: class Node {... }; class Iterator {... }; void insert(Node *object) { object->next = first.next; first.next = object; }.... private: Node first; // Dummy record }; class List { public: class Node {... }; class Iterator {... }; void insert(Node *object) { object->next = first.next; first.next = object; }.... private: Node first; // Dummy record }; Nested type definition are used mainly for scope definition and for minimizing the pollution of the global name space. Indeed, the Ansi-C++ committee decided to add a namespace keyword to C++.

bEgInSlIdE OOP-7 uDeclare and initialize - List::iterator i(mid_east) uInitialize - i.reset() uGet element - Value of i.next() uIncrement - i.next() uCheck if last - Cast to int. If 0 then list exhausted. List Iterators... List::Iterator i(mid_east); for (; i; ((Leader *)i.next())->print()) ;... for (i.reset(); i; ((Leader *)i.next())->print()) ;... List::Iterator i(mid_east); for (; i; ((Leader *)i.next())->print()) ;... for (i.reset(); i; ((Leader *)i.next())->print()) ; Is next a mutator or an observer?

bEgInSlIdE OOP-8 Inheritance and Heterogeneous Containers class List {... class Node { Node *next; Node(Node *n): next(n) {} friend class List; protected: Node(void): next(NULL) {} virtual ~Node(void) { delete next; } };... }; class List {... class Node { Node *next; Node(Node *n): next(n) {} friend class List; protected: Node(void): next(NULL) {} virtual ~Node(void) { delete next; } };... }; Recursive deletion is not terribly efficient... Note that delete NULL is perfectly legal in C++! uThe List::Node data type is nothing but its identity and linkage information. uThe List data type may contain any type derived from List::Node.

bEgInSlIdE OOP-9 Inheriting From List::Node #include class Leader: public List::Node { String name; String country; public: Leader(const char *n, const char *c): name(n), country(c) {} void print(void) { cout << name << ';' << country << '\n'; } }; #include class Leader: public List::Node { String name; String country; public: Leader(const char *n, const char *c): name(n), country(c) {} void print(void) { cout << name << ';' << country << '\n'; } }; u Leader ’s constructor will invoke List::Node ’s default constructor u Leader ’s destructor will invoke List::Node ’s destructor

bEgInSlIdE OOP-10 The Type Hierarchy so Far List List::Node List::Iterator Leader uThe nested class definitions are done only for minimizing pollution of the global name space

bEgInSlIdE OOP-11 New & Delete class List {... class Node {... protected: virtual ~Node(void) {... } public: void *operator new(size_t size) { return ::operator new(size); void operator delete(void *p, size_t size) { ::operator delete(p); };... }; class List {... class Node {... protected: virtual ~Node(void) {... } public: void *operator new(size_t size) { return ::operator new(size); void operator delete(void *p, size_t size) { ::operator delete(p); };... }; Employee::new for all classes derived from Employee Always static, even if not declared as such! The size parameter is that of the actual object allocated/deallocated.

bEgInSlIdE OOP-12 Protected Data Members uDerived classes cannot access private parts (Or else it would have been a breach of privacy) uProtected data and methods can be accessed only by: lderived classes lmembers lfriends

bEgInSlIdE OOP-13 Protected Constructors class List { public: class Iterator; class Node { friend class List; friend class Iterator; Node *next; Node(Node *n): next(n) {} protected: Node(void): next(0) {} virtual ~Node(void) { delete next; } };... }; class List { public: class Iterator; class Node { friend class List; friend class Iterator; Node *next; Node(Node *n): next(n) {} protected: Node(void): next(0) {} virtual ~Node(void) { delete next; } };... }; uThe next field and the non-default constructor can be used by List and List::Iterator only. u Leader can only use the default constructor of List::Node.

bEgInSlIdE OOP-14 List Destruction and Virtual Destructors List class List {... class Node {... protected: virtual ~Node(void) { delete next; } }; Node first; }; class List {... class Node {... protected: virtual ~Node(void) { delete next; } }; Node first; }; uDestruction sequence l List goes out of scope lט List destructed lט First node destructed lט Other nodes destructed recursively u ~List::Node must be virtual to guarantee that ~Leader is called when the list is destructed Leader Node Leader Node Leader Node

bEgInSlIdE OOP-15 Iterator Implementation class List {... class public: class Iterator { Node *first, *curr; public: Iterator(List& l) { first = &l.first; reset(); } void reset(void) { curr = first->next; } operator int(void) { return curr != NULL; } Node *next(void) { Node* tmp = curr; if (curr != NULL) curr = curr->next; return tmp; } };... Node first; // Dummy node used as first list element }; class List {... class public: class Iterator { Node *first, *curr; public: Iterator(List& l) { first = &l.first; reset(); } void reset(void) { curr = first->next; } operator int(void) { return curr != NULL; } Node *next(void) { Node* tmp = curr; if (curr != NULL) curr = curr->next; return tmp; } };... Node first; // Dummy node used as first list element };

bEgInSlIdE OOP-16 Summary: List Interface class List { public: class Node {... }; class Iterator {... }; void insert(Node *object) { object->next = first.next; first.next = object; } }; class List { public: class Node {... }; class Iterator {... }; void insert(Node *object) { object->next = first.next; first.next = object; } }; u List stores any class derived from List::Node. uExported operations are insert and iteration Only. uConstructor and destructor are generated automatically.

bEgInSlIdE OOP-17 Quiz void driver(void) { List mid_east; mid_east.insert(new Leader("Assad","Syria")); mid_east.insert(new Leader("Peres","Israel")); mid_east.insert(new Leader("Hussein","Jordan")); List::Iterator i(mid_east); for (; i; ((Leader *)i.next())->print()) ; mid_east.insert(new Leader("Mubarak","Egypt")); for (i.reset(); i; ((Leader *)i.next())->print()) ; } void driver(void) { List mid_east; mid_east.insert(new Leader("Assad","Syria")); mid_east.insert(new Leader("Peres","Israel")); mid_east.insert(new Leader("Hussein","Jordan")); List::Iterator i(mid_east); for (; i; ((Leader *)i.next())->print()) ; mid_east.insert(new Leader("Mubarak","Egypt")); for (i.reset(); i; ((Leader *)i.next())->print()) ; } uWhat will be printed? uDescribe the allocation and deallocation activities. uHow is the following an indication of a design problem? l ((Leader *)i.next())->print()

bEgInSlIdE OOP-18 class List {... class Iterator { Node *first, *curr; Node *next(void) { Node* tmp = curr; if (curr != NULL) curr = curr->next; return tmp; } public: Iterator(List& l) { first = curr = l.first.next; } void reset(void) { curr = first; } operator int(void) { return curr != NULL; } Node * operator()(void){ return curr; } Iterator& operator++(void){ next(); return *this; } };... };... for (List::Iterator i(mid_east); i; ++i) cout << *(Leader *)i(); class List {... class Iterator { Node *first, *curr; Node *next(void) { Node* tmp = curr; if (curr != NULL) curr = curr->next; return tmp; } public: Iterator(List& l) { first = curr = l.first.next; } void reset(void) { curr = first; } operator int(void) { return curr != NULL; } Node * operator()(void){ return curr; } Iterator& operator++(void){ next(); return *this; } };... };... for (List::Iterator i(mid_east); i; ++i) cout << *(Leader *)i(); Operator Overloading & Iterators Why prefix operator++ ? Assumption: operator<< is overloaded for class Leader

bEgInSlIdE OOP-19 Iteration Functions void ForEach(List& list, void (*func)(List::Node *current)) { for (List::Iterator i(l); i; ++i) func(i()); } List::Node *FirstThat(List& list, int (*func)(List::Node *current)) { List::Node *current; for (List::Iterator i(l); i; ++i) if (func(current = i())) return current; return (List::Node *)0; } void ForEach(List& list, void (*func)(List::Node *current)) { for (List::Iterator i(l); i; ++i) func(i()); } List::Node *FirstThat(List& list, int (*func)(List::Node *current)) { List::Node *current; for (List::Iterator i(l); i; ++i) if (func(current = i())) return current; return (List::Node *)0; } uCan be used for implementing general purpose iteration and search

bEgInSlIdE OOP-20 Using Iteration Functions void Print(List::Node *n) { cout << (Leader *)n; }... ForEach(mid_east,Print);... Leader Who, *found;... int Search(List::Node *n) { return (Leader *)n == Who; }... if ((found = FirstThat(mid_east,Search)) != NULL)... void Print(List::Node *n) { cout << (Leader *)n; }... ForEach(mid_east,Print);... Leader Who, *found;... int Search(List::Node *n) { return (Leader *)n == Who; }... if ((found = FirstThat(mid_east,Search)) != NULL)...

bEgInSlIdE OOP-21 Memory Allocation Responsibilities: Summary and Typical Errors uBetter to store pointers in a container uBetter let the container own the elements: l Elements destroyed when container destroyed. uTypical errors are: lStore an automatic object lStore a global/static object lStore the same object in more than one container. lDestroying explicitly an element in the container.