Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 1 Composition: Cooperating Classes Composition.

Slides:



Advertisements
Similar presentations
Linear Lists – Array Representation
Advertisements

DATA STRUCTURES USING C++ Chapter 5
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 1 Exceptions exceptiona program.
Class and Objects.
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,
Chapter 14: Overloading and Templates
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Linked List and Namespace ~ include dynamic objects.
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.
Data Structures Using C++ 2E
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
Classes Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd Spetember 2006.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
OBJECT ORIENTED PROGRAMMING LECTURE 12 Instructor: Rashi Garg Coordinator: Gaurav Saxena.
Controlling Inheritance Data Structures & OO Development I 1 Computer Science Dept Va Tech May 2006 ©2006 McQuain & Ribbens Inheritance Modes When deriving.
Design & Evaluation OO Software Design and Construction Computer Science Dept Va Tech February 2000 ©2000 McQuain WD 1 Class Design and Evaluation Class.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
1 C++ Syntax and Semantics, and the Program Development Process.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
Object-Oriented Programming in C++
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
1 Chapter 16 Linked Structures Dale/Weems/Headington.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
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:
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Communication OO Software Design and Construction Computer Science Dept Va Tech February 2001 ©2001 McQuain WD & Keller BJ 1 Communicating Objects Think.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
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.
C++ Inheritance Data Structures & OO Development I 1 Computer Science Dept Va Tech June 2007 © McQuain Generalization versus Abstraction Abstraction:simplify.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
1 Linked Multiple Queues. 2 A real world example. Not in the book. Sometimes we have a fixed number of items that move around among a fixed set of queues.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
Memory Management.
CS505 Data Structures and Algorithms
Review: Two Programming Paradigms
Lists The List ADT.
This pointer, Dynamic memory allocation, Constructors and Destructor
Chapter 16-2 Linked Structures
Chapter 4 Linked Lists.
Introduction to Classes
Chapter 4 Linked Lists.
Chapter 16 Linked Structures
CS410 – Software Engineering Lecture #5: C++ Basics III
Managing 2D Arrays Simple Dynamic Allocation
Lists CMSC 202, Version 4/02.
Data Abstraction: The Walls
Presentation transcript:

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 1 Composition: Cooperating Classes Composition of Classes Composition by Association A Simple Association Composition by Aggregation A Simple Aggregation Composition for Flexibility Communicating Objects Communication: inter-Object Communication Communication: Passing an Object Communication: Returning an Object Composition Example: Simple Array of Objects Aggregation Example: Fancy Array of Objects Aggregation and Constructor Sequencing Aggregation and Destructor Sequencing Anonymous Objects and Returned Objects One Last Aggregation Puzzler Typical Aggregation Sequencing Controlling Aggregation Sequencing Different Ways to Communicate Characteristics of Communicated Objects

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 2 Composition of Classes Composition:an organized collection of components interacting to achieve a coherent, common behavior. Why compose classes? Permits a “lego block” approach to design and implementation: Each object captures one reusable concept. Composition conveys design intent clearly. Improves readability of code. Promotes reuse of existing implementation components. Simplifies propagation of change throughout a design or an implementation.

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 3 Composition by Association Association (acquaintance) Example: a database object may be associated with a file stream object. The database object is “acquainted” with the file stream and may use its public interface to accomplish certain tasks. Acquaintance may be one-way or two-way. Association is managed by having a “handle” on the other object. Associated objects have independent existence (as opposed to one being a sub-part of the other). Association is generally established dynamically (at run-time), although the design of one of the classes must make a provision for creating and maintaining the association. Sometimes referred to as the “knows-a” relationship.

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 4 A Simple Association class DisplayableNumber { private: int Count; ostream* Out; public: DisplayableNumber(int InitCount = 0, ostream& Where = cout); void ShowIn(ostream& setOut); void Show() const; void Reset(int newValue); int Value() const; }; void DisplayableNumber::ShowIn(ostream& setOut) { Out = &setOut; } void DisplayableNumber::Show() const { *Out << Count << endl; }

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 5 Composition by Aggregation Aggregation (containment) Example: a LinkList object contains a Head pointer to the first element of a linked list of Node objects, which are only created and used within the context of a LinkList object. The objects do not have independent existence; one object is a component or sub- part of the other object. Aggregation is generally established within the class definition. However, the connection may be established by pointers whose values are not determined until run-time. Sometimes referred to as the “has-a” relationship.

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 6 A Simple Aggregation class Array { // static-sized array encapsulation private: int Capacity; // maximum number of elements list can hold int Usage; // number of elements list currently holds Item* List; // the list void ShiftTailUp(int Start); void ShiftTailDown(int Start); void Swap(Item& First, Item& Second); public: Array(); // empty list of size zero Array(int initCapacity); // empty list of size initCapacity Array(int initCapacity, Item Value); // list of size initCapacity, // each cell stores Value Array(const Array& oldArray); // copy constructor int getCapacity() const; // retrieve Capacity int getUsage() const; // Usage bool isFull() const; // ask if List is full bool isEmpty() const; // or empty //... continues...

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 7 A Simple Aggregation //... continued bool InsertAtTail(Item newValue); // insert newValue at tail of list bool InsertAtIndex(Item newValue, int Idx);// insert newValue at specified // position in List bool DeleteAtIndex(int Idx); // delete element at given index bool DeleteValue(Item Value); // delete all copies of Value in list Item Retrieve(int Idx) const; // retrieve value at given index int FindValue(Item Value) const; // find index of first occurrence of // given value void Clear(); // clear list to be empty, size zero void Reverse(); // reverse order of list elements ~Array(); // destroy list (deallocate memory) };

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 8 Composition for Flexibility The use of composition not only promotes the reuse of existing implementations, but also provides for more flexible implementations and improved encapsulation: Next “Data Socket” Data Element Here we have a design for a list node object that:  separates the structural components (list pointers) from the data values  allows the list node to store ANY type of data element class LinkNode { private: ItemType Data; // data “capsule” LinkNode* Next; // pointer to next node public: LinkNode(); LinkNode(ItemType newData); void setData(ItemType newData); void setNext(LinkNode* newNext); ItemType getData() const; LinkNode* getNext() const; };

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 9 Communicating Objects Think of the “Borg”on Star Trek. Borg crew member= 1 object Borg Collective= composition of objects To achieve the purpose of the Collective, each Borg must continually communicate with other Borg. A Borg can be a “sender” or a “receiver”, and may play both roles at different times. Similarly, objects can be senders or receivers.

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 10 Communication: inter-Object Communication By name: sender “knows the name” of the receiver and uses the name to access the public interface of the receiver. DisplayableNumber D(42, cout); D.Show(); // D accesses cout by its pointer member void DisplayableNumber::Show() const { *Out << Count << endl; }

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 11 Communication: Passing an Object An object may be passed as a function parameter: DisplayableNumber D(42, cout); ofstream oFile(“output.text”); D.ShowIn(oFile); // D receives oFile as a parameter void DisplayableNumber::ShowIn(ostream& setOut) { Out = &setOut; // store address of setOut } As is always the case in C++, by default an object parameter is passed by value to the called function.

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 12 Communication: Returning an Object An object may be the return value from a function: typedef DisplayableNumber Item; // define an alias const int Digits = 10; Array LCD(Digits, Item(0, cout)); // array of DNs... DisplayableNumber Digit4 = LCD.Retrieve(4); // shallow copy... Using an object as the return value provides a mechanism for encapsulating a body of related heterogeneous data (as does using a struct). Item ArrayClass::Retrieve(Item Idx) const { if (Idx >= Usage) return -1; else return List[Idx]; }

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 13 Composition Example: Simple Array of Objects #include using namespace std; #include "DisplayableNumber.h" const int Digits = 5; void main() { DisplayableNumber* LCD = new DisplayableNumber[Digits]; for (int Idx = 0; Idx < Digits; Idx++) { LCD[Idx].Show(); } delete [] LCD; } Constructing: DisplayableNumber 0 Destructing: DisplayableNumber If the constructors and destructors are instrumented, this program produces the output:

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 14 Aggregation Example: Fancy Array of Objects #include using namespace std; #include "Array.h" const int Digits = 5; void main() { Array LCD(Digits, Item(0, cout)); for (int Idx = 0; Idx < Digits; Idx++) { LCD.Retrieve(Idx).Show(); } Array.h #includes Item.h, which contains: #include “DisplayableNumber.h” typedef DisplayableNumber Item; Note use of a nameless, or “anonymous” object. Note use of member function of the returned DisplayableNumber object.

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 15 Aggregation Example: Fancy Array of Objects #include using namespace std; #include "Array.h" const int Digits = 5; void main() { Array LCD(Digits, Item(0, cout)); for (int Idx = 0; Idx < Digits; Idx++) { LCD.Retrieve(Idx).Show(); } Constructing: DisplayableNumber Constructing: Array Constructing: DisplayableNumber Destructing: DisplayableNumber 0 Destructing: DisplayableNumber 0 Destructing: DisplayableNumber 0 Destructing: DisplayableNumber 0 Destructing: DisplayableNumber 0 Destructing: DisplayableNumber Destructing: Array Destructing: DisplayableNumber ? ? ? ? ? If the constructors and destructors are instrumented, this program produces the output shown. There are a few subtleties illustrated here…

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 16 Aggregation and Constructor Sequencing const int Digits = 5;... Array LCD(Digits, Item(0, cout)); Constructing: DisplayableNumber Constructing: Array Constructing: DisplayableNumber ? Here, the sub-objects are constructed AFTER the Array object is constructed. The reason is fairly clear if the Array constructor is examined: Array::Array(int initCapacity, Item Value) { Capacity = initCapacity; Usage = Current = 0; List = new Item[initCapacity]; for (int Idx = 0; Idx < Capacity; Idx++) List[Idx] = Value; Usage = Capacity; } Here, the array elements don’t exist until the Array constructor creates the array dynamically.

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 17 Aggregation and Destructor Sequencing #include using namespace std; #include "Array.h" const int Digits = 5; void main() { Array LCD(Digits, Item(0, cout));... }... Destructing: DisplayableNumber... Destructing: Array Destructing: DisplayableNumber The anonymous DisplayableNumber object constructed in the Array constructor call is destructed when the call completes. Also, since it is passed by value, a copy is made within the constructor, and the copy is also destructed when the call completes. When main() terminates, the Array object is destructed. The Array destructor delete s its array, and that causes the destruction of each array clement.

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 18 Anonymous Objects and Returned Objects... for (int Idx = 0; Idx < Digits; Idx++) { LCD.Retrieve(Idx).Show(); }... 0 Destructing: DisplayableNumber 0 Destructing: DisplayableNumber 0 Destructing: DisplayableNumber 0 Destructing: DisplayableNumber 0 Destructing: DisplayableNumber... On each pass through the for loop, an anonymous object is created and then destructed (when it goes out of scope at the end of the loop). But, why are no constructor calls shown? Item Array::Retrieve(int Idx) const { if (Idx >= Usage) return Item(); else return List[Idx]; } Because the return value is created by a copy constructor (not instrumented).

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 19 One Last Aggregation Puzzler class Foo { private: DisplayableNumber DN; public: Foo(); Foo(DisplayableNumber DN); ~Foo(); }; Now, the DisplayableNumber is a data member; it is created when a Foo object is created. (TRUE aggregation) Foo::Foo() { cout << "Constructing: Foo" << endl; DN = DisplayableNumber(0, cout); } Foo::Foo(DisplayableNumber DN) { cout << "Constructing: Foo" << endl; this->DN = DN; } Foo::~Foo() { cout << "Destructing: Foo" << endl; } DisplayableNumber myDN(17, cout); Foo urFoo(myDN); Constructing: DisplayableNumber... Constructing: DisplayableNumber Constructing: Foo Destructing: DisplayableNumber... Destructing: Foo Destructing: DisplayableNumber

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 20 Typical Aggregation Sequencing In a typical aggregation, where the sub-objects are data members (not allocated dynamically), the following rules hold for constructor and destructor sequencing: Construction: the default constructor is invoked for each sub-object, then the constructor for the containing object is invoked. So, aggregates are constructed from the inside-out. Destruction:the destructor is invoked for the containing object first, and then the destructor for each sub-object is invoked. So, aggregates are destructed from the outside-in. It’s also possible to invoke a non-default constructor for a sub-object...

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 21 Controlling Aggregation Sequencing Constructors for sub-objects may be explicitly invoked BEFORE the body of the containing object’s constructor: Here, a DisplayableNumber constructor is invoked and passed two parameters (which could have been parameters to the Foo constructor if that had been appropriate). Foo::Foo() : DN(0, cout) { cout << "Constructing: Foo" << endl; }

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 22 Different Ways to Communicate Is object communicated by: copying reference pointer Can the receiver modify the object? If the receiver does modify the object, does the sender see the changes? What language syntax is used in receiver to access (. or -> )?

Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 23 Characteristics of Communicated Objects TechniqueCopiedChangeableVisibleC++ Syntax by copyyesyesno. by referencenoyesyes. by pointernoyesyes -> by const referencenonono. by const pointernonono -> By Copy: 4 Sender is “isolated” from changes by receiver 8 No good if sender/receiver want to share object 8 Bad if object is large (why?) By Identity (pointer or reference): 8 No isolation 4 Permits sharing of objects 4 Improves memory cost for large objects