Today s lecture. CS 314 fall 01 C++ 1, page 1

Similar documents
Chapter 11. Abstract Data Types and Encapsulation Concepts

September 10,

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.

CS201 - Introduction to Programming Glossary By

Short Notes of CS201

Data Abstraction. Hwansoo Han

Concepts of Programming Languages

CMSC 4023 Chapter 11

10. Abstract Data Types

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Overview of today s lecture. Quick recap of previous C lectures. Introduction to C programming, lecture 2. Abstract data type - Stack example

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

COMP 2355 Introduction to Systems Programming

CPS 506 Comparative Programming Languages. Programming Language

Abstract Data Types and Encapsulation Concepts

CSCI387 Data Structure Fall. Aug. 21, 2012 Sung Hee Park Computer Science Virginia State University

Programming Languages 2nd edition Tucker and Noonan"

What are the characteristics of Object Oriented programming language?

CLASSES AND OBJECTS IN JAVA

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Overview of C++: Part 1

Implementing Subprograms

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

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

OBJECT ORIENTED PROGRAMMING USING C++

Chapter 1: Object-Oriented Programming Using C++

DATA TYPES. CS 403: Types and Classes DATA TYPES (CONT D)

Object Oriented Paradigm

Midterm Exam (REGULAR SECTION)

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

Chapter 11. Abstract Data Types and Encapsulation Concepts 抽象数据类型 与封装结构. 孟小亮 Xiaoliang MENG, 答疑 ISBN

Subtyping (Dynamic Polymorphism)

Abstract data types &

Abstract Data Types & Object-Oriented Programming

CSE 303: Concepts and Tools for Software Development

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli

C++ Programming: Polymorphism

G Programming Languages Spring 2010 Lecture 8. Robert Grimm, New York University

Topics. Modularity and Object-Oriented Programming. Dijkstra s Example (1969) Stepwise Refinement. Modular program development

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

C++ (Non for C Programmer) (BT307) 40 Hours

Evolution of Programming Languages

Chapter 19: Program Design. Chapter 19. Program Design. Copyright 2008 W. W. Norton & Company. All rights reserved.

COSC252: Programming Languages: Abstraction and OOP. Jeremy Bolton, PhD Asst Teaching Professor. Copyright 2015 Pearson. All rights reserved.

CS304 Object Oriented Programming Final Term

Fast Introduction to Object Oriented Programming and C++


Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Lecture 18 Tao Wang 1

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

! Mon, May 5, 2:00PM to 4:30PM. ! Closed book, closed notes, clean desk. ! Comprehensive (covers entire course) ! 30% of your final grade

You must include this cover sheet. Either type up the assignment using theory3.tex, or print out this PDF.

Object-Oriented Programming

JAVA: A Primer. By: Amrita Rajagopal

Two approaches. array lists linked lists. There are two approaches that you can take:

Object Oriented Design

Introduction to Programming Using Java (98-388)

ECE 449 OOP and Computer Simulation Lecture 14 Final Exam Review

CS 216 Exam 1 Fall SOLUTION

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Lecture Notes on Programming Languages

G Programming Languages - Fall 2012

CS11 Introduction to C++ Fall Lecture 7

G Programming Languages - Fall 2012

JAVA MOCK TEST JAVA MOCK TEST II

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

G52CPP C++ Programming Lecture 9

Inheritance. Transitivity

Lecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques

Goals of this Lecture

Chapter 11. Abstract Data Types and Encapsulation Concepts

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)

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

Week 8: Operator overloading

Object Oriented Software Design II

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Modular Programming. Prof. Clarkson Fall Today s music: "Giorgio By Moroder" by Daft Punk

Derived Classes in C++

Ch. 11: References & the Copy-Constructor. - continued -

Chapter 10 Introduction to Classes

CS558 Programming Languages

eingebetteter Systeme

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

Where do we go from here?

Chapter 6 Introduction to Defining Classes

Chapter 10 :: Data Abstraction and Object Orientation

Class Information ANNOUCEMENTS

G52CPP C++ Programming Lecture 13

Interview Questions of C++

Written by John Bell for CS 342, Spring 2018

Fundamentals of Programming Languages

Lecture 15a Persistent Memory & Shared Pointers

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

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

Compiler Construction Lent Term 2015 Lectures 10, 11 (of 16)

Object Oriented Programming. Solved MCQs - Part 2

Transcription:

Today s lecture Midterm Thursday, October 25, 6:10-7:30pm general information, conflicts Object oriented programming Abstract data types (ADT) Object oriented design C++ classes CS 314 fall 01 C++ 1, page 1

Midterm date: October 25, 6:10-7:30pm. location: TBA Closed book, closed notes, 80 minutes exam.you need to bring a picture ID to the exam!!! There will be no class on Thursday, October 25. CONFLICT (see p.8 in Undergraduate Schedule): Another Common Hour Exam at the same time. Another regularly scheduled class at the same time. Another regularly scheduled recitation at the same time. YOU NEED TO ASK YOUR PROFESSOR TO SEND EMAIL TO RYDER@CS TO CONFIRM THE CONFLICT If you have a conflict, you need to sign-up in the conflict sheet. Give the exact reason for your conflict (course number, regularly scheduled hour or common hour exam,...). CS 314 fall 01 C++ 1, page 2

Historic Progression of Data Types 1. User-defined types Can define arbitrary operations Transparent: whole structure of type visible Cannot control access to structure 2. Abstract data types Encapsulation, information hiding Opaque: hides data representation Access restricted to well-defined interface functions 3. Object-orientation Inheritance Code re-use Polymorphic behavior CS 314 fall 01 C++ 1, page 3

Data Abstraction Specification rather than implementation: Define behavior of data type (through interface functions) Hide implementation of data type hide details irrelevant to the use of the data type CS 314 fall 01 C++ 1, page 4

User-defined Stack Type in C subset of C++ #include <stream.h> typedef int bool; typedef int elt; #define MAX 20 #define EMPTY -1 typedef struct {elt s[max]; int top; } stack; stack * create() { stack * newstack = (stack *)malloc(sizeof(stack)); newstack->top = EMPTY; return (newstack); } void push(stack* stk,elt data) {stk->s[++stk->top]=data;} void pop(stack* stk) {stk->top--;} elt peek(stack* stk) {return (stk->s[stk->top]);} int main() { /**** using the stack ****/ stack *x; /* stack of indefinite lifetime */ x = create(); push(x,2); push(x,3); cout << peek(x) << "\n";} CS 314 fall 01 C++ 1, page 5

Problems with Data Types Implementation of the type can be seen (E.g., the array inside the stack) Users of the type can change its value arbitrarily E.g., x->s[5] = 10; doesn t respect push/top access pattern doesn t respect elt typedef Users of the data type can write operations that create inconsistent states (E.g., adding an entry without changing the top index) Users cannot extend the set of operations in a reliably safe fashion CS 314 fall 01 C++ 1, page 6

Abstract Data Types (ADTs) User may only manipulate objects of the type through use of provided functions without knowing internal representation Encapsulation: may only use provided functions Information hiding: cannot see internal representation CS 314 fall 01 C++ 1, page 7

Advantages of Abstract Data Types Easier to use: as if only type names and function headers were visible Safety through access control User can t make inconsistent states User can t make assumptions about data representation Designer of ADT can modify implementation without affecting users Encourages modularity in programs, facilitating larger, more complex systems CS 314 fall 01 C++ 1, page 8

Designing an Abstract Data Type 1. Specify interface 2. Identify and maintain invariants Example: bounded stack Interface: Stack of some kind of element elt create makes a new, empty stack push pushes new element on stack; cannot push onto full stack pop removes an element; cannot pop from empty stack peek returns the top element on stack is empty determines if the stack is empty is full determines if the stack is empty CS 314 fall 01 C++ 1, page 9

Invariants peek(push(s, e)) = e pop(push(s, e)) = S is empty(create()) not is empty(push(s, e)) not is full(pop(s)) CS 314 fall 01 C++ 1, page 10

Object-Oriented Programming (OOP) Similar to abstract data types Allows users to build new types Encapsulation Information hiding Allows code sharing or reuse between related types: inheritance Theory of object-oriented programming is not finished First object oriented language: Simula 67 Different languages work differently Syntax can be complicated Semantics may be ill-defined CS 314 fall 01 C++ 1, page 11

Object-Oriented Design Design: What components? How do they interact? Example: an elevator control system Elevator control panel buttons lights door speaker Floor control panel buttons lights door indicator lights Control system multiple floors multiple elevators location optimizer CS 314 fall 01 C++ 1, page 12

Example Observe Different parts of system are independent, with limited interfaces Implementation of any one portion can easily be changed Objects can be composed of other objects Same kind of object may appear in lots of places CS 314 fall 01 C++ 1, page 13

Guidelines of OOP Access to data should be as restricted as possible: Each class controls its data A class should have access to all and only the data it needs to perform its work CS 314 fall 01 C++ 1, page 14

C++ Classes Describe abstract data types Encapsulate data and define operations on it Class definitions Define data members (variables) Define member functions (or methods) Access restriction: public and private Objects are instances of classes CS 314 fall 01 C++ 1, page 15

ADT Stack in C++ // statically allocated stack ADT #define MAX 20 // default stack size typedef int elt ; typedef int boolean; class stack{ // encapsulated data type private: elt s[max]; // int top; // hidden data representation const int EMPTY = -1; // public: stack() { top = EMPTY; } // constructor => create() boolean isempty() { return (top == EMPTY); } boolean isfull() { return (top == MAX - 1); } void push(elt data) { if (!isfull()) s[++top]=data; else cout<<" stack is full; cannot push\n"; } void pop() { if (!isempty()) top--; else cout<<" stack is empty; cannot pop\n"; } }; elt peek() { if (!isempty()) return s[top]; else cout<<" stack is empty; cannot peek\n"; } CS 314 fall 01 C++ 1, page 16

Constructors and Destructors Define a constructor, called to initialize objects (object instances) of the class (constructors may take arguments) May define a destructor, called to free heap memory used by objects Constructors and destructors for class X: constructor: X(...) destructor: ~X() Constructor called implicitly when object is allocated (created) Destructor called implicitly when control leaves scope of object (end of object s lifetime). CS 314 fall 01 C++ 1, page 17

ADT Stack in C++ // dynamically allocated stack ADT typedef struct cell { elt info; struct cell* link; } CellType; class stack{ private: CellType * top; public: stack() {top=null;} ~stack() { while (top!= NULL) pop(); } boolean isempty() { return (top == NULL); } boolean isfull() { return 0; } void push(elt data) { CellType* add = new CellType; add->info = data; add->link = top; top = add; } void pop() { CellType* tmp; tmp = top; top = top->link; delete tmp; } // no error check }; elt peek() { return (top->info); } // no error check CS 314 fall 01 C++ 1, page 18

Functions (and Operators) in C++ Function body can be defined outside class definition. Still need function interface (signature) declaration in class definition. (Somewhat similar idea: foo.h and foo.c file) Functions can have optional parameters. Functions and operators can be overloaded: Have different implementations on different types Must be distinguishable by type signature Like + on int and float CS 314 fall 01 C++ 1, page 19

ADT Stack in C++ class stack{ private: CellType * top; public: stack(); ~stack(); boolean isempty(); boolean isfull(); void push(elt data); void pop(); elt peek(); }; stack::stack() { top=null; } stack::~stack() { while (top!= NULL) pop(); } boolean stack::isempty() { return (top == NULL); } boolean stack::isfull() { return 0; } void stack::push(elt data) { CellType* add = new CellType; add->info = data; add->link = top; top = add; } void stack::pop() { CellType* tmp; tmp = top; top = top->link; delete tmp; } // no error check elt stack::peek() { return (top->info); }// no error check CS 314 fall 01 C++ 1, page 20

Efficiency in OO Code Encapsulation and information hiding imply many function calls. Function calls have high run-time overhead. Efficient compilers inline calls where possible: Function code is expanded at point of call Like a macro larger, unreadable machine code faster machine code CS 314 fall 01 C++ 1, page 21

How to deal with large software systems? Imperative, top down structured programming Involves writing the program in very high level descriptions and successively refining these into lower level descriptions, always maintaining a correct program. Abstraction levels are driven by task granularities. Often the same or very similar pieces of code are used in different parts of the program. Object oriented design based on simulation of the application world. The basic entities of the application domain become the entities in the solution domain from which the program is build up. Object oriented design begins from the data and builds programs from the bottom up. Separation of specification (abstraction) and implementation. CS 314 fall 01 C++ 1, page 22

Object oriented design Advantages: Allows reuse of abstractions in many different settings since typical application domains have commonly used abstractions. Abstractions can be reimplemented using different data structures without affecting the design of the program at a higher level (abstract data types (ADTs), representation independence). CS 314 fall 01 C++ 1, page 23

Object oriented paradigm Objects basic entity in the solution domain object is a set of services that correspond to an abstraction from the application domain. objects simulate real world entities that they are supposed to model, for instance, a lion, a machine, a stack, an employee. objects that provide the same set of services are in the same class (have same type) in the solution domain. All objects in the same class have the same interface. CS 314 fall 01 C++ 1, page 24

Terminology Object oriented analysis analysis of the application domain to understand the basic entities, their characteristics, and the relationships among them. Object oriented design process of designing a collection of classes and objects to simulate the entities in the application domain. Object oriented programming process of implementing an object oriented design in a suitable programming language, such as C++, Java, Smalltalk,... CS 314 fall 01 C++ 1, page 25

Object oriented programming How to write an object oriented program in C++? Identify the entities What entity should be an object in the solution world (level of abstraction, different implementations, potential for reuse)? Identify the behavior of entities What are the services? Identify the relationships between entities Example: is one entity a specialization of another? Create a C++ design structure for the entities What is the public interface of C++ classes to represent entity types? CS 314 fall 01 C++ 1, page 26

Relationships among entities There are a number of important relationships among entities that are useful in object oriented design, e.g.: is a AnentitytypeT1isintheis a relationship to another entity type T2 if every entity of type T1 is a member of type T2. In the solution domain, this is represented as a relationship between classes implemented using (public) inheritance (T2 corresponds to base class or superclass, and T1 corresponds to derived class or subclass). has a An entity e 1 is in the has a relationship with entity e 2,ife 2 is part of e 1 or e 1 uses e 2 for implementation. There are two types of the has a relationship: class level (complete containment) or instance level (share instance via pointer). uses a Occurs when one class instance takes another class instance as a parameter. For example, a manager might use a particular company facility. In this case, facility is not a manager, nor it is owned by manager. CS 314 fall 01 C++ 1, page 27

Example: Is a and has a relationships Employee Manager Clerical Worker Secretary Staff Writer has a is a CS 314 fall 01 C++ 1, page 28

Inheritance in Object-Oriented Languages Subtypes: A subtype S of type T: any operation that can apply to object t of type T can apply to object s of type S. Any object s of type S can be used in any context that an object of type T can. Inheritance: Provides a means of subtyping and sharing code. Allows redefinition of operations. In C++, terminology is base classes and derived classes. CS 314 fall 01 C++ 1, page 29

C++ Derived Classes Inherit (data and function) members from base class. We use public inheritance. May have its own constructors and/or destructors. Its own constructors/destructors may explicitly or implicitly call base class constructors/destructors. CS 314 fall 01 C++ 1, page 30

Example: Is a and has a relationships #include <stream.h> class Employee { public: int ID; Employee(int id) {ID = id;} }; class ClericalWorker : public Employee { public: int group; ClericalWorker(int id, int grp) : Employee(id) {group = grp;} }; class Secretary : public ClericalWorker { public: char *name; Secretary(int id, int grp) : ClericalWorker(id, grp) {} }; class StaffWriter : public ClericalWorker { public: char *name; StaffWriter(int id, int grp) : ClericalWorker(id, grp) {} }; class Manager : public Employee { public: int devision; Secretary *assistant; Manager(int id, char *nm) : Employee(id) {assistant = new Secretary(++id,1); assistant->name = nm;} }; main() { Manager Bob(123, "Steve"); } cout << "Manager Bob (ID " << Bob.ID << ") works with " << Bob.assistant->name << " (ID " << Bob.assistant->ID << ")\n"; CS 314 fall 01 C++ 1, page 31