information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/sinformatici/mat/...  ·...

139

Upload: trandiep

Post on 05-Feb-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design
Page 2: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

C M T 2 0 5 0Object Oriented

Programming and Design

Module Handbook

Semester 22001/2002

Lecturer: Dr. Xiaohong Gao

School of Computing Science

2

Page 3: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Contents

CONTENTS.............................................................................................................................................2

1. AN OVERVIEW..................................................................................................................................6

1.1 PREFACE.......................................................................................................................................6

1.2 THE MODULE TEACHING TEAM...........................................................................................6

1.3 ABOUT THIS HANDBOOK........................................................................................................6

2LEARNING UNIT NARRATIVE (LUN) ---- OFFICIAL MODULE INFORMATION..........................................8

COURSEWORK....................................................................................................................................10

THE LOGBOOK.....................................................................................................................................10WEB PAGES.........................................................................................................................................10THE SHORT PROGRAMMING TASKS......................................................................................................12THE INDIVIDUAL PROJECT...................................................................................................................12THE GROUP PROJECT...........................................................................................................................12COURSE WORK 1 ---- Short Program Task 1..........................................................................13COURSE WORK 2 ---- Short Program Task 2..........................................................................15COURSE WORK 3 ---- Short Program Task 3..........................................................................17COURSE WORK 4 ---- Individual Program Project...........................................................19COURSE WORK 5 ---- Group Project ........................................................................................21

LECTURE PLAN..................................................................................................................................24

3. LECTURES........................................................................................................................................25

LECTURE 1 OBJECT-ORIENTED PROGRAMMING (OOP).....................................................25

1.1 PROCEDURAL PROGRAMMING...................................................................................................251.2 OBJECT-ORIENTED PROGRAMMING...........................................................................................25

LECTURE 2 CLASSES AND DATA ENCAPSULATION.............................................................27

2.1 INTRODUCTION..........................................................................................................................27An example of class:.......................................................................................................................27

2.2 CLASSES....................................................................................................................................282.3 EXAMPLE PROGRAM USING CLASSES.......................................................................................29

Example Class Definition...............................................................................................................29Example Class Implementation......................................................................................................30

2.4 DATA ENCAPSULATION.............................................................................................................31Diagram of Data Encapsulation....................................................................................................31

LECTURE 3 ABSTRACTION AND CONSTRUCTORS...............................................................32

3.1 ABSTRACTION...........................................................................................................................32An Interface and Implementation of a Cassette Player..................................................................32

3.2 AN INTRODUCTION TO CONSTRUCTORS...................................................................................323.3 COPY CONSTRUCTOR................................................................................................................34

LECTURE 4 POINTER (*) AND DESTRUCTOR (~)....................................................................35

4.1 MEMORY AND THE WHOLE MACHINE.......................................................................................35Operating System Core (Kernel)....................................................................................................35Processes........................................................................................................................................35Disk Cache.....................................................................................................................................35

4.2 MEMORY AND THE PROCESS.....................................................................................................36Executable Machine Code..............................................................................................................36

3

Page 4: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Static Memory................................................................................................................................36Stack Memory.................................................................................................................................36Dynamic Memory...........................................................................................................................36

4.3 POINTERS..................................................................................................................................37KEY FACTS....................................................................................................................................37

4.3.1 AN EXAMPLE OF ACCESSING AN ARRAY USING POINTERS.................................................394.4 PRINCIPLES OF DYNAMIC MEMORY...........................................................................................404.4.1 OBJECTS ON THE HEAP.........................................................................................................41

KEY FACTS....................................................................................................................................414.4.2 ARRAYS ON THE HEAP.........................................................................................................41

KEY FACTS....................................................................................................................................414.5 THE DESTRUCTOR.....................................................................................................................42

LECTURE 5 POLYMORPHISM......................................................................................................43

5.1 SOME DEFINITIONS...................................................................................................................43Overloading The use of the same (function) name for similar facilities....................................43

5.2 OVERLOADING ORDINARY FUNCTIONS....................................................................................435.3 DEFAULTING FUNCTION ARGUMENTS......................................................................................43

An Example of Defaulting Function Arguments............................................................................445.4 OVERLOADING CONSTRUCTORS...............................................................................................454.6 AN EXAMPLE OF OVERLOADING CONSTRUCTORS...................................................................45

LECTURE 6 COMPOSITION AND INHERITANCE.....................................................................46

6.1 RELATIONSHIPS "HAS-A" VERSUS "IS-A".............................................................................466.2 COMPOSITION IN PRACTICE......................................................................................................466.3 INHERITANCE............................................................................................................................47

What is inheritance ?.....................................................................................................................47Example:........................................................................................................................................47

6.4 PUBLIC, PRIVATE AND PROTECTED MEMBERS..........................................................................486.5 PUBLIC, PRIVATE AND PROTECTED DERIVATIONS...................................................................49

Derived Class Access.....................................................................................................................49

LECTURE 7 OBJECT-ORIENTED DESIGN USING UML...........................................................51

7.1 DESIGN.......................................................................................................................................517.2 UML..........................................................................................................................................517.3 USE CASE DIAGRAM...................................................................................................................527.4 USE CARE DIAGRAM EXAMPLES................................................................................................52

LECTURE 8 STATIC DATA MEMBERS AND METHODS,.......................................................54

STATIC BINDING AND DYNAMIC BINDING.............................................................................55

8.1 STATIC MEMBER VARIABLES...................................................................................................558.2 STATIC MEMBER FUNCTIONS...................................................................................................558.3 STATIC BINDING........................................................................................................................568.4 DYNAMIC BINDING....................................................................................................................568.5 AN EXAMPLE OF DYNAMIC BINDING........................................................................................57

Step 1..............................................................................................................................................58Step 2..............................................................................................................................................59Step 3..............................................................................................................................................59

LECTURE 9 ADVANCED TECHNIQUES (1)................................................................................61

9.1 INLINE FUNCTION..........................................................................................................................619.2 INLINE MEMBER FUNCTIONS....................................................................................................629.3 IMPLICIT INLINING....................................................................................................................639.4 FRIENDSHIP IN PRINCIPLE.........................................................................................................64

What ?............................................................................................................................................64Why ?..............................................................................................................................................64How ?.............................................................................................................................................64

4

Page 5: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

9.5 GRANTING FRIENDSHIP TO AN ORDINARY FUNCTION..............................................................65HINTS.............................................................................................................................................65

9.6 GRANTING FRIENDSHIP TO A METHOD OF ANOTHER CLASS...................................................669.7 GRANTING FRIENDSHIP TO ANOTHER CLASS...........................................................................67

LECTURE 10 ADVANCED TECHNIQUES (2)................................................................................68

10.1 OPERATOR OVERLOADING - IN PRINCIPLE..........................................................................6810.2 OPERATOR OVERLOADING - THE EQUALITY TEST................................................................6910.3 OPERATOR OVERLOADING - ASSIGNMENT...........................................................................70

LECTURE 11 TEMPLATES (EXTRA READING)..........................................................................71

11.1 FUNCTION TEMPLATES.........................................................................................................71What are function templates ?........................................................................................................71Why use function templates?..........................................................................................................71

11.2 EXAMPLE CODE WITHOUT FUNCTION TEMPLATES...............................................................7111.3 CREATING A FUNCTION TEMPLATE......................................................................................7211.4 USING FUNCTION TEMPLATES..............................................................................................7211.5 FUNCTION TEMPLATES WITH MULTIPLE DATA TYPES..........................................................7311.6 CLASS TEMPLATES...............................................................................................................74

Example program using the class template....................................................................................7611.7 CONTAINER CLASSES AND THE S.T.L..................................................................................77

4 MATERIALS FOR LECTURES................................................................................................78

5. MATERIALS FOR SEMINARS................................................................................................79

SEMINAR 1. PRE-PROCESSORS.....................................................................................................79

1.2 THE PHASES OF COMPILATION..................................................................................................801.3 THE ROLE OF THE PREPROCESSOR............................................................................................83

SEMINAR 2. EXERICES.....................................................................................................................85

SEMINAR 3 EXERCISES..................................................................................................................88

SEMINAR 4 EXERCISES..................................................................................................................89

SEMINAR 5 EXERCISES...................................................................................................................90

SEMINAR 6 EXERCISES..................................................................................................................91

SEMINAR 7-10 GROUP PROJECT MEETING..............................................................................91

SEMINAR 11 GROUP PROJECT PRESENTATION......................................................................91

MATERIALS FOR LABS....................................................................................................................92

LAB 1. USING C++ BUILDER TO CREATE PROJECTS............................................................92

LAB 2 EXERCISES............................................................................................................................93

LAB 3 EXERCISES............................................................................................................................93

LAB 4 EXERCISES............................................................................................................................94

LAB 5 EXERCISES............................................................................................................................95

LAB 6 EXERCISES............................................................................................................................95

LAB 7 EXERCISES............................................................................................................................95

5

Page 6: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

LAB 8 EXERCISES............................................................................................................................95

LAB 9 EXERCISES............................................................................................................................96

LAB 10 EXERCISES........................................................................................................................96

LAB 11 EXERCISE..........................................................................................................................96

LAB 12 EXERCISE..........................................................................................................................96

6. SAMPLE EXAM PAPER …………………………………………………………… 93

6

Page 7: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

1. An Overview

1.1 Preface

Welcome to the module of Object Oriented Programming (OOP) and Design. This module aims to provide: An introduction to the concepts of object orientation using C++. An opportunity to enable students to re-use classes from the C++ libraries

provided. The techniques to design and develop a software using UML (Unified Modeling

Language).

It is hoped the this module challenging, informative, relvant and enjoyable.

Any suggestions and evaluations about this module handbook and all other aspects of your learning experiences of this mudole over the coming semester will be warmly received and welcome.

Xiaohong Gao, module leaderBounds Green, office 2C23Telephone : 020 8411 2252Email: [email protected]

http://www.cs.mdx.ac.uk/staffpages/xiaohong/

1.2 The module teaching team

Member of staff Role Email Telephone Office

Dr. Xiaohong Gao Module LeaderLecturesLabsSeminars

x.gao 2252 2C23

Mike Batchelor Labs, Seminars

m.batchelor

1.3 About this Handbook

This handbook is not a complete set of learning materials for the work in the module. In addition to handbook, there is a recommended core text, seminars, computer labs and lectures. Students need to make full use of all these learning resources, and beyond – using materials from object oriented programming and C++ programming

7

Page 8: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

books in the libraries (e.g. at Bounds Green), following up materials from lectures by readling, seminars and practical work in the labs and your own time.

1.4 Overall Learning Objectives of CMT2050

The learning objectives of a module are the things that you should be able to do at the end of module. The coursework and exams are the estimation methods to test whether you have achieved the objectives. On passing the module you will be confident at writing object oriented programs using C++ language.

At the end of module you will be able to:

Describe the application of object oriented principles in the process of program design.

Discuss and critique the implementation quality of a set of classes. Using C++ to write classes and libraries. Using UML to design a software system with object oritation.

1.5 Acknowlegements This handbook has been built upon materials originally authored by Alastair Measures, Janet Rix, and many other members in CMT group. Their contributions are gratefully acknowledged.

8

Page 9: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

2 Learning Unit Narrative (LUN) ---- Official Module Information

MODULE CODE CMT2050TITLE OBJECT ORIENTED PROGRAMMING AND DESIGNLEVEL 2 CREDIT POINTS 20PRE-REQUISITE CMT1501 or equivalent

AIMS /CATALOGUE ENTRYThis module aims to deepen your understanding of object-oriented concepts. It introduces an abstract modelling notation (UML) and puts theory into practice with C++. The module is designed to enable the students to both reuse classes from the libraries provided and to design and develop new classes.

SYLLABUS data abstraction, abstract data types and class design. class design using a graphicak notation such as UML. classes; constructors, destructors, instances, default constructors methods / member functions, virtual functions, pure and null functions data types; public, private and protected class hierarchies; inheritance, overloading, polymorphism container classes, ownership friend functions and friend classes. templates and template libraries

LEARNING OUTCOMES At the end of this module you should be able to:-

Knowledge explain the software engineering issues and objectives leading to object

orientation. explain the principles of encapsulation, inheritance and polymorphism. describe the application of object oriented principles in the process of program

design. explain the object oriented features and syntax of C++. design and analysis an object-oriented software using UML.

LEARNING OUTCOMES -- SKILLS

Cognitive Skills discuss and critique the design quality of a set of classes expressed in UML. discuss and critique the implementation quality of a set of classes implemented in

C++.

Subject Specific Skills use C++ to write classes. use software tools to build programs from re-usable components. Implement an object-oriented design with appropriate C++ features.

9

Page 10: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Express the design of a class library in a clear and systemaatic manner using UML.

Transferable Skills working together with peers in preparing a group project report and presentation.

TEACHING AND LEARNING STRATEGIES Weekly lectures will deliver theory and principles with the aid of examples. Weekly seminars will build on the lectures with practical design exercises and

group problem solving. Weekly supervised laboratory sessions will support students to strengthen their

programming skills. Weekly self-study will be used for reading, studying the examples provided and

completing assessed tasks.

LEARNING MATERIALSCore Texts Jo Ann Smith, DEVELOPING PROJECTS USING OBJECT ORIENTED C++.

International Thomson Publishers, 1999. ISBN 0-7600-1107-9.

Additional Texts H. M. Deitel and P. J. Deitel, C++ How to Program, 2/e. Prentice Hall, 1998.

ISBN 0-13-528910-6 R. C. LEE and W. M. Tepfenhart, UML and C++, A Protical Guide to

Object_Oriented Development, 2nd ed., Prentice Hall, 2001. ISBN 0-13-029040-8.

ASSESSMENT SCHEMEUnseen Examination 40 % 3 questions from 5Coursework 20 % Short ProgramsCoursework 20 % Individual ProjectCoursework 20 % Group Project

LEARNING UNIT CONTACT DURATIONS PER WEEKLecture 1:30Seminars 1:00Laboratory 1:30Total Study Hours per Semester 180:00

10

Page 11: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Coursework

For this module: the coursework forms 60% of the assessment, relative to the exam which forms the remaining 40%. This recognises and rewards the higher level of effort that the coursework for this module demands.

The coursework for this module includes several parts: short programming tasks, a group project and an individual project. Students are required to attempt all three parts. Each of the three parts of the coursework accounts for one third of the coursework marks.

The Logbook

The logbook must have a copy of the “logbook cover sheet” [copy from next page] attached to the outside of the front cover. Do remember to fill in all the necessary details on the cover sheet.

The logbook should accumulate marked copies of your short programming tasks and individual projects. It is regarded as normal to have several versions of the same task as your skills improve in the light of feedback from your tutor.

Your programs and diagrams should be printed out, glued in and signed off (by your tutor) at the earliest opportunity. Please note that marks cannot be awarded without evidence (paper copies) of the work. This applies no matter what has been lost, stolen or vomitted upon by the dog!. Your programs and diagrams should be printed out, glued in and signed off (by your tutor) at the earliest opportunity.

The logbooks should be submitted to the student office before the end of the semester.Please note that work contained in your logbook is not marked after you submit it to the student office at the end of the semester. After the end of the semester: the logbooks are needed for quality assurance purposes; such as checking the quality and consistency of marking. This checking is done by internal and external moderators.

Web Pages

Using the module home page you will be able to access documents detailing each piece of coursework you are required to do. Each document will supply:

Cover Page: when relevantThe Task: exactly what you are being asked to provide.The Learning Objective: why this tasks is a good thing to do.Guidance on Deliverables: advice and guidance to help you.The Marking Criteria: how a grade is decided.The Deadline: when it should be done by.

11

Page 12: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

CMT 2050:Object Oriented Programming and Design

Semester 2, 2001/2002 Logbook Cover Page

DEADLINE: 3:00pm, 13th May 2002

Family Name

First Name

Student Number

Marks for the Coursework

Grade Lab tutor Signature

Grade Lab Tutor Signature

Short 1 Individual project

Short 2

Short 3 Group Project

Page 13: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Module Leader: Dr. Xiaohong GaoSchool of Computing ScienceBounds Green Email: [email protected] Ext: 2252Room: 2C23

13

Page 14: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

The short programming tasks

These tasks are intended to develop your understanding of the constructs and techniques introduced in lectures. You should complete each, and get it assessed in your programming laboratory, before moving on to the next.

These tasks should be demonstrated and marked in the programming laboratory time. You may get a particular task assessed more than once, if it was not up to the standard required originally. Your tutor can explain any problems on screen or when it is assessed. You may also be asked questions about your program, or be asked to make changes to prove that you understand it. On satisfactory completion: you should printout a copy of the program and glue it into a logbook. The tutor must also make a note on their master mark sheet and initial each page of your program, and also sign your logbook cover sheet appropriately.

There will be a number of these “Short Programming Tasks” and they will be available on the module web pages, complete with marking criteria et cetera.

The Individual Project

These projects are intended to allow you demonstrate your understanding and capability in developing software using the constructs and techniques covered by this module.

You should choose one of the topics and develop your project based around it. If there is a different topic which interests you and is of similar complexity to the ones listed then you may attempt it; but only with the agreement of your tutor and lecturer. The purpose of requiring such agreement is to prevent students attempting projects which are too ambitious or that risk taking up too much of their time. If you have a topic in mind then please type up an outline description of the topic and show it to you tutor and then to your lecturer.

There will be a number of suggested project outlines available on the module web pages together with marking criteria et cetera.

The Group Project

This requires students to work together in teams. There should be between three and five students in a team. The project team should look at the task together and agree to delegate specific tasks to individual members of the team. The team should work at providing an analysis of the problem, designing a solution and providing samples of what the code would look like. Time will be made available during seminars for teams to meet and discuss their project.

Each group should deliver a report to the student office and after that they will be required (as a group) to deliver a five minute presentation on their report and recommendations. This presentation will be made in seminar time and will end with time for questions and answers.

The details of this assignment will be on the module web page.

14

Page 15: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Short Programming Task 1 ---- to be assessed in Week 3/4 (7% of total marks)

Using Video class, create a Nurse class to keep nurses’ records. The Nurse class should include at least the following data members: name gender age working place Rank (e.g., superintendent, junior, senior)

The main program (nursemain.cpp) should provide interface for inputting nurse’s data and outputting these data.

Guidance on Deliverables

Pages 1-3: All of your source code (cpp and h files). All of your source code (cpp and h files) should have consistent indentation to a clear style.

All program listings are to go into the students’ logbook.

15

Page 16: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

The Marking Criteria (for short program task 1).

The following are indicative evidence for achieving the corresponding level. You must meet ALL the criteria for a level to have reached that level.

Q: Missing

No demonstration given.

F: Fail

The Nurse class is an exact copy of the (say) Video class. No additional data members and functions are provided. Test program fails to instantiated objects of the Nurse class. Test program does not attempt to call the requested member functions.

P: Pass

Nurse class based on Video class with most of the additional data members Most of the member functions are provided as requested An object of class Nurse is instantiated by the test program Test program calls most of the requested member functions. Comments are relevant to the additional code. Student demonstrates understanding of classes, objects, data members and member functions.

M: Merit

Nurse class based on Video class with all additional data members Separate member functions are provided to (e.g., change working place, change rank, display nurse

name, display working place, display rank ). An object of class of Nurse is instantiated by the test program. Test program calls all the requested member functions. Comments are relevant to the additional code. Student demonstrates understanding of classes, objects, data members and member functions.

D: Distinction

In addition to the criteria of Merit Level: Data validation is performed by the set functions Two constructors (including the default) should be supplied. The new set member functions are called by the constructors and other relevant functions.

The Deadline

This task should be completed and marked by the end of week 3/ 4 !

16

Page 17: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Task 2: ---- to be assessed by Week 6 (7%of total marks)

Modify the following class for Airplane to include at least: Two more constructors. Declare “type” using pointer. Add a data member “date” using pointer type (e.g., 01-02-1950) to indicate the date

when the airplane was registered.

(the original 3 sample files (airplane.h, airplane.cpp, main.cpp ) are in L:\2001-02\Cmt2050\week2)

//ariplane.h

#ifndef AIRPLANE_H#define AIRPLANE_H

class Airplane{public: Airplane(); void set_type(char*); void set_current_speed(double); void set_max_speed(double); const char* get_type(); double get_current_speed(); double get_max_speed();

private: char type[50]; double current_speed; double max_speed;};

17

Page 18: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Task 2 Marking Scheme

The following are indicative evidence for achieving the corresponding level. You must meet ALL the criteria for a level to have reached that level.

Q: Missing No demonstration given. Program code not handed in to student office.

F: Fail Program is exactly the same as in week 2 directory at L drive.

P: Pass Two constructors are given. Airplane type is declared as pointer and implemented using new or delete where appropriate.

M: Merit Two constructors are given. Pointer types are given to the Airplane type. new and delete are used properly to reflect pointer types in all the places where type is given new values.

D: Distinction In addition to the criteria for Merit, Methods should be marked const where appropriate. A data member date is given as pointer type and is properly reflected using new and delete where

appropriate. A member function is created to access date data member. A reasonable interface should be given for changing current speed.

18

Page 19: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Short programming task 3 ---- to be marked in week 9 (10% of total mark)

Create a list of student records. The student class should include the following data members:

name age gender date of enrollment degree to study (e.g., BSc, fundation, HND)

Guidance on Deliverables

The date of enrollment should form a separate class and include at least day month year

An array of student records should be created.

19

Page 20: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Task 3 Marking Scheme

The following are indicative evidence for achieving the corresponding level. You must meet ALL the criteria for a level to have reached that level.

Q: Missing No demonstration given. Program code not handed in to student office.

F: Fail Two classes with some (public) methods and (private) member variables. Test program does not attempt to call the requested member functions. Some comments at the head of each source file.

P: Pass A date class contains appropriate member variables. A Student class contains appropriate member variables. Implement a reasonable set of "set" and "get" functions on each class. Implement at least a default constructor for each class. An object of stuRecord class is created by the test program and includes date class. Test program does attempt to call the requested member functions. Each class has a separate header (.h) file and source code (.cpp) file.

M: Merit An array of student records is created. Test functions create an instance for input before outputting it. Each implemented member function should have a descriptive comment. Student demonstrates understanding of composition and constructors.

D: Distinction Data validation is performed by all the set functions Two constructors (including the default) should be supplied for each class. The "set" methods are called by the constructors and other relevant functions. Methods should be marked const where appropriate. A reasonable interface is created.

20

Page 21: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Programming project ---- to be marked in week 12 (16% of total marks)

A programming project should be chosen to demonstrate your understanding of and ability to use the different constructs and concepts covered in the course.

The programming project should be demonstrated and marked in the programming labs. You are expected to develop your program in stages – modifying your earlier version to include extra functionality.

A print out of all project files and associated documentation together with the program files for each of the short programming tasks, must be handed in to the student office by 3:00pm, Monday 13th May.

Suggested projects are given below. You choose one of these projects (only one).

Design and implement a set of classes to print out Student records in an alphabetical order by last name. The program should include Part-time students class and full time student class.

Part time student might have working place, time to study, e.g., evening, one day per week, years to finish degree (4 years, 6 years).

Full time students might have A-level, GCSE results.

Design and implement a set of classes to record residencies for a district council. The program should print out the residencies in an alphabetical order by last name.

Each family might have father, mother, and children. Father or mother should have occupation, working place. Children should have name of school.

Design and implement a set of classes for a vehicle registration and print out all the registered vehicle in an alphabetical by their plates.

Vehicles at least include cars and motorbike. Each vehicle should have model, type, etc.. Each registration should include the owner, owner’s address, registration

number, price of the vehicle.

21

Page 22: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Programming project Marking Scheme

The following are indicative evidence for achieving the corresponding level. You must meet ALL the criteria for a level to have reached that level.

Q: Missing No demonstration given Program code not handed in to student office

F: Fail The class or set of classes does not fulfill one of the project outlines. Test program fails to instantiate objects of the new classes. Test program does not successfully call member functions of the new classes.

P: Pass Coherent sets of classes, which include derived classes, have been designed to fulfil the

chosen project outline. The test program provides a basic interface to the new classes, with a limited range of functions

suitable for the chosen project. The test program instantiates an object of at least one of the new classes. Test program successfully calls several of the member functions for the new classes. Comments are relevant to the code Student demonstrates understanding of the classes presented.

M: Merit A coherent set of classes, which includes derived classes, has been designed to fulfil the chosen

project outline. At least, 7 files (4 .cpp files, 3 .h files) are given, i.e, two inherited classes are given. The test program provides a sensible user interface to the new classes, with a good range of functions

suitable for the chosen project. The test program instantiates objects of relevant classes. Test program is capable of successfully calling all of the member functions for the new classes. Comments are relevant to the codeThe student has demonstrated understanding and sensible use of most of the following techniques:

Base classes, Inherited classes and Inheritance. Const functions and data members. Private, protected and public access mechanisms.

D: DistinctionAll evidence required as for Merit level above and: The test program provides a comprehensive user interface to the new classes, with a wide range of

functions suitable for the chosen project. The student has also demonstrated understanding and sensible use at least FOUR of the following

techniques: Composition, friendship, overloading, copy constructor, dynamic memory, operator overloading, inline function.

File input/output is used with relevant data files.OR 2 or more aspect of complexity and new techniques implemented.

22

Page 23: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Group Project (10% for presentation and 10% for report )

In your seminar class you should form into groups with 2 to 4 students, time will be made available from Week 7 (March 18) for the group to work together during time tabled seminar sessions. As a group you must complete the assigned task, prepare a written report, and make a presentation outlining your recommendations to the rest of the seminar class.

The tasks (choose one) :

1. Use UML to design a Library Information System with facilities of Borrowing including fines for over due items Returning Indexing new items/books Deleting some old items/books Providing electronic information

2. Use UML to design a Travel Agency System with facilities of Holiday/Air ticket booking via interviewing Holiday/Air ticket booking via telephone Holiday/Air ticket booking via internet

3. Use UML to design a Banking System with facilities of Personal account including current and save accounts Telephone banking Personal information

The written report must include the following:

A list of group members names and student numbers. An outline of the tasks allocated to each person at different stages

(e.g. analysis, design , written report, presentation, etc). – Signed and agreed by all team members.

Details of group meetings (minutes of meetings). Design of the system using UML.

Identifying nouns for the system via interviewing or other means. Identifying classes Some class diagrams Some use case diagrams Full class diagram using UML notation

Source code for selected examples of member functions Appendix of information collected if there are any.

The overall grade will be given on the basis of:

the degree to which all members of the group have contributed to the task,and how well the group have worked together (allocated tasks, etc).

the quality of the report the quality of the presentation

The presentation will be in the seminar of week 11 and will last about 10-15 mins. After the presentation there will be a question and answer session. Every member of the group will be expected to answer at least one question.

23

Page 24: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Each group will be given a grade. Every member of the group will thus get the same grade. The exception to this is that any individual who does not attend the presentation or sign the task outline will be given a Q grade.

The report will be handed in to the Student Office with LogBook by May 13, Monday. Each member of the group will have a copy of the report in his/her logbook.

24

Page 25: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

CMT2050: Presentation marking guidelines

The following are intended to give an idea of the level of presentation skill required to get a particular grade. They describe the minimum skill level to achieve the grade. They are just a guideline for the marker. If you make most of the points for a particular level, allowance may be made for other points. The marker’s decision is final.

DistinctionTalk well structured with clear sign-posting of sectionsHigh quality visual aids (something special about them)Highly enthusiastic – maintains interest throughoutLogical argument

MeritTalk has structure (introduction, middle, end)Good use of visual aidsEnthusiasticAttempt at logical argument

SatisfactoryAttempt to structure talk – e.g. introduction but shaky on conclusionTalk audible and understandableTalk is on topic setIf problems with visual aids (eg blocked) noticesWinds up smoothly to time.Good eye contact throughout

PassLittle structure to talkAbout topic setNo use of visual aids or poor quality visual aids (eg too small to read)Occasionally halting deliveryOver runs on time and is cut short rather than winding up smoothlySome eye contact

ReferralNo structureOnly barely about topicNo use of visual aidsInaudible for much of timeOver runs and continues for significant time after being wound upNo eye contact

FailTalk abandoned part way throughInaudibleNo visual aids usedOff topic

Q: Did not give a presentation (a fail grade)

25

Page 26: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture Plan ---- CMT 2050

Dates Week Title Lab Seminar WeekFeb. 4

- Feb. 81 Object Oriented Programming (OOP) &

Borland C++ Builder 5Build a project andshort programming task 1

The cycle of Programming 1

Feb.11 -Feb. 15

2 Classes and Data Encapsulation Classes and short programming task 1

exercises 2

Feb. 18 - Feb. 22

3 Abstractors and constrcutors ConstructorsShort programming task 1 Marking

Exercises 3

Feb. 25 - Mar. 1

4 Pointers (*) & Destrcutor (~) Pointer &Short programming task 1 Marking

Exercises 4

Mar. 4- Mar. 8

5 Polymorphism Function overloadingTask 2

Exercises 5

Mar. 11- Mar. 15

6 Composition and inheritance (1) CompositionTask 2 Marking

Exercises 6

Mar. 18- Mar. 22

7 OO Design using UML InheritanceTask 3

ExercisesIntroduction to group project

7

Mar. 25- Mar. 29

E1 Week 1 of Easter break E1

Apr. 1- Apr. 5

E2 Week 2 of Easter Break E2

Apr. 8- Apr. 12

8 Composition and inheritance (2) Task 3 Group project meeting 8

Apr. 15- Apr. 19

9 Static data members, methods,& Static binding and dynamic binding

Task 3 MarkingIndividual Project

Group project meeting 9

Apr. 22- Apr. 26

10 Advanced C++ Techniques (1) Inline functions, friend functionsIndividual project

Group project presentationMarking

10

Apr. 29- May 3

11 Advanced C++ Techniques (2) Operator overloadingIndividual project

Group project presentationMarking

11

May 6- May 10

12 Revision Individual project marking Submission of Log-Book by3:00pm, 13/05/2001

12

26

Page 27: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

27

Page 28: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

3. Lectures

Lecture 1 Object-Oriented Programming (OOP)

1.1 Procedural Programming

Programs ---- consist of modules, which are parts that can be designed, coded, and tested separately and then assembled.

Procedural Programming (such as C language) ---- the modules are procedures. In C, a function is a procedure. C language is a procedural language in which a program’s modules are its functions. Designing a procedural program is known as top-down design. Example 1 ---- print out an integer number, a character, and a double number.

Figure 1.1 relationship between data and the functions in procedural programming.

1.2 Object-Oriented Programming

Is another way of thinking about programming. The focus is on the relationship between data and tasks, rather than on a program’s tasks. A program contains objects that respond to messages sent to them. A message (or function call) is simply a request for the object to do something. In C++, you create objects that contain data and actions or behaviors that the object is capable

of performing. These actions, called methods (or member functions), are implemented by writing functions

that are part of object itself. Example 2 --- print out an integer number, a character, and a double number. In example 2, the relationship between data and the methods is built into the object itself. After an object named print_obj is created, it knows how to print_int(), print_char(), and

print_double(). Data are not passed to these methods. The object knows how to print the values of the data members that belong to the same object. E.g., print_obj.print_char() sends the print_char() message to the print_obj object. The print_obj object responses by printing the character stored in its data member.

29

int x = 10;

10print_int(x);

char ch=’a’;

a

print_char(ch);

double d = 3.14159;

3.14159

Print_double(d);

Page 29: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Figure 2.1 Relationship between data and the methods in object-oriented programming.

Exercise:1. Using an example to explain the differences between procedural programming and object-oriented programming.

30

Print_obj

int x 10

char ch a

double d 3.14159

print _int();

print_char()

print_double();

Print print_obj; // create objectprint_obj.print_int(); //send messageprint_obj.print_char(); //send messageprint_obj.print_double(); //send message

Page 30: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture 2 Classes and Data Encapsulation

2.1 Introduction

Object Oriented (OO) Programming is a data oriented approach to program design.

A major idea behind object orientation involves observing that programs attempt to simulate interactions with (and between) “things” in the real world.

An OO program is consisted of classes that are building blocks.

A class has a collection of member variables (fields to contain values).

A class also has a collection of methods (functions to carry out actions associated with the class).

Methods are also referred to as member functions.

An instance of a class is known as an object.

Classes are also known as abstract data types in object oriented terminology. These are data types that can be used almost anywhere that ordinary (atomic) data types like float can. Physical data types like int and float are already well known to the compiler; whereas classes we create are not.

An example of class:

class umbrella{// DEFINE MEMBER VARIABLES WITH DATA TYPESprivate:

float length;float diameter;float weight;

// DEFINE PROTOTYPES FOR MEMBER FUNCTIONSpublic:

void print_diameter ( );void print_area ( );

};

31

Page 31: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

2.2 Classes

A class is an abstract data type. An instance of a class is called an object.

In the same way that a function has a prototype and an implementation; a class has a definition, which specifies the interface and an implementation which codes the task.

A class definition has the general form:

class aclassname{private:

// private member declarations (member variables) go here

public:// public member declarations (member functions) go here

}; // NOTE: semicolon is needed

The public section of the class definition marks out those parts which form the interface which can be used from elsewhere.

The private section of the class definition marks out those parts which are hidden members of the class and not available for external use.

The private and public sections do not need to be in a specific sequence; and, there can be many public and private sections within a class definition (though it is usually simpler to group items).

Essential good practice involves making all member variables private and most member functions public.

32

Page 32: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

2.3 Example Program Using Classes

// program.cpp

#include <iostream.h>#include "video.h"

void main ( ){

// Create an object Video vid1;

// Invoke various methods on the objectvid1.set_all ( "Titanic", "Cameron Co", 40);cout << vid1.get_name ( ) << endl;cout << vid1.get_producer ( ) << endl;

}

Example Class Definition

// file: video.h

const int SIZE = 40;

class Video{private:

char name[SIZE];char producer[SIZE];short quantity;

public:void set_all (char*, char*, short);char *get_name();char *get_producer();short get_quantity();

}; // semicolon is needed !

33

Page 33: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Example Class Implementation

// file: video.cpp

#include <string.h>#include "video.h"

void Video::set_all (char *v_name, char *prod, short qty){

strcpy (name, v_name);strcpy (producer, prod);quantity = qty;

}

char *Video::get_name( ){

return name;}

char *Video::get_producer( ){

return producer;}

short Video::get_quantity( ){

return quantity;}

Video::Video ( ){

strcpy (name, "");strcpy (producer, "");quantity = 0;

}

34

Page 34: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

2.4 Data Encapsulation

There are four important features that object oriented programming supports. They are:1. Data encapsulation2. Data abstraction3. Data polymorphism4. Data inheritance

Data Encapsulation means hiding (and therefore protecting) the member variables within an object so that they can only be accessed by member functions. Other (non member) functions must call a member function to access data for them. Data encapsulation is a key feature of Object Orientation.

Diagram of Data Encapsulation

Encapsulation allows us to hold information in whatever representation we choose without the code that uses a class being aware. Encapsulation allows us to change our mind and rewrite the class (implementation) in question without needing to change anything else.

There is a class definition and a separate class implementation. The definition sets out the interface of a class: entailing all that is sufficient for other code to be able to use the class. The interface sets out a list of the member variables and a list of member functions (similar to function prototypes). The implementation sets out the workings of the algorithms.

35

Page 35: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture 3 Abstraction and Constructors

3.1 Abstraction

Encapsulation allows us to create abstractions. We are all familiar with cassette players since they all have similar interfaces though we don’t need to know the details of how it works (thankfully). An abstraction allows us to treat entities as "black boxes". The programmers using an abstraction know how to "talk" to it but not how its internals work.

An abstraction has a publicly defined interface; which is often simple and logical. An abstraction also has an implementation; which can often be complex and involved. For a programmer to use an abstraction; they only need to understand its interface.

Many of the system functions are procedural abstractions; take for example the square root function in C++ which is called sqrt. To use it we only need to know the following:

its purpose and name the number of arguments the type and meaning of each argument the type and meaning of the return value

As well as procedural abstractions; we can have abstract data types which can be manipulated via a defined interface without understanding the underlying data storage or algorithms. In C++ we call abstract data types classes. These help us to build up large and sophisticated programs by not demanding that we understand all the various levels of detail at one time.

An Interface and Implementation of a Cassette Player.

3.2 An Introduction to Constructors

A constructor is a special member function used to initialise an object as it is created.A programmer can use constructors to ensure that every member variable is set to a value and that none are left un-initialised.

36

Page 36: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Object creation involves invoking a constructor automatically; whichever way that object is created.

A class does not have to have a constructor; but that will leave the object un-initialised and is very bad practice.

Using a constructor to initialise every member variable removes a whole category of (uninitialised value) bugs; which can be very difficult to locate. Failure to use constructors properly makes such bugs almost inevitable. It is seen as essential good practice to have a constructor for every class you write. The time it takes to write a constructor is limited ….. the time it can take to locate a bug is not !!.

The default constructor has no parameters and is used when objects are created as local variables. Even when you appear to be (just) declaring a variable: the constructor is automatically used.

Constructors have the same name as the class they belong to and should not have a return value specified. Constructors are usually public … otherwise they are unavailable to functions such as main.

See the example in section 2.3 where the class definition includes the constructor:

public:Video ( );

The class implementation also includes the constructor:

Video::Video ( ){

strcpy (name, "");strcpy (producer, "");quantity = 0;

}

37

Page 37: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

3.3 Copy Constructor

The copy constructor is a special constructor that is invoked when an object is created and initialised with the values stored in the data members of an existing object. The copy constructor is called when any of the following events occur:

A new object is created using an existing object. An object is passed by value to a function. An object is returned from a function.

The copy constructor always takes one argument, a constant reference to a class object, e.g,

Video (const Video&);

38

Page 38: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture 4 Pointer (*) and Destructor (~)

4.1 Memory and the whole machine

Operating System Core (Kernel)

This is the code which implements the central capabilities of the operating system: such as virtual memory, time sharing and access to file and network functions. This is loaded (booted) as the computer starts and stays resident thereafter.

Processes

These are the programs running on the computer. Many of the these will be your applications; though others will be in the background monitoring facilities such as the queue of documents to be printed.

Disk Cache

This is memory used to keep speed up the disk accesses. This speeds up many applications because often data being read has been recently written to disk. On some systems (Windows 3.1) this is of fixed size; though on modern operating systems this expands dynamically to use all currently free memory.

39

Page 39: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

4.2 Memory and the process

A process is a name for a running program (e.g., MSWord, C++ Builder). There can be many instances of a program running at one time. Each process has separate memory associated with it. This process memory has several component parts.

Executable Machine Code

This contains the executable instructions which instruct the processor what to do. This is formed as a result of the compilation process and represents the functions written by a programmer. The size of this component does not change (and neither should it's contents!!).

Static Memory

This contains the global constants and variables of a program. This component of a program does not change in size or location through the life of the process. Global variables (declared outside any function or class) appear here; as do local variable marked as static. Unless there is a very good reason: it is bad style to declare a variable outside a function.

Stack Memory

Stack variables come into being as the function called and last for the time that the function is active. As a function calls another function: the parameter functions are placed on the stack; followed by variables declared within the called function. Any return value also travels via the stack. Local variables (declared in a function) are (by default) stack variables. Function parameters are also stack variables. Stack variables are only visible within the function where they are declared. Notice that a function can call itself; each nested call has a different instance of the local stack variables. A function calling itself: is called recursion and it can provide simple and elegant solutions to particular tasks.

Dynamic Memory

In addition to the other components: there is a pool of available memory from which amounts can be "borrowed" rather like from a lending library. This permits a program to hold an elastic amount of data. On a modern operating system: the size of this pool of memory can be expanded whilst the process is running by using virtual memory. These pieces of memory are accessed by use of pointers.

40

Page 40: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

4.3 Pointers

A pointer is a variable that holds the address of another variable

For example: char * cp;int * ip;

KEY FACTS

A pointer is a type of variable. It points to a value elsewhere, rather than housing the value itself.

A pointer is declared and used in relation to the data type to which it points. A pointer variable which you do not wish to point to a specific variable: is usually set to NULL.

NULL is not a keyword in C++; instead it is a #define value which comes in when you: #include < iostream.h >

The NULL value may be used irrespective of pointer type. The void* data type is the way that untyped pointers are declared. Rather than meaning a

pointer to nothing: this actually means a pointer to anything.

Untyped pointer variables can be assigned values from other pointer types.

Untyped pointer variables can be compared with values from other pointer types: as happens with the NULL value.

An untyped pointer variable cannot legally be dereferenced since it doesn't point to any defined data type.

Pointers can be assigned to indicate the location of a variable or even of some spare memory on the heap.

A pointer being incremented (or decremented): moves by the size of whatever data type it points to. This allows, for example, simple stepping through an array. This principle applies to all the arithmetic operators and to all data types including objects and structures.

41

Page 41: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

#include <iostream.h>

void main (){int j = 33;int k;int *pp;

pp = &j; // Point to an integer

k = *pp / 11; // Use indicated integer

cout << k;}

// end of file

42

Page 42: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

4.3.1 An Example of Accessing an Array using Pointers

//// FILE: totaller.cpp// AUTHOR: Alastair Measures// DATED: October 1999// DESCRIPTION: Array totalling using a pointer//

#include <iostream.h>

float totalup (int arraysize, float *farray);

void main (){

float array[10] ={

3.1, 1.3, 2.4, 1.0, 9.2,5.6, 3.2, 4.5, 6.7, 8.9

};cout << totalup (10, array);

}

float totalup (int arraysize, float *farray){float total = 0.0;

while (arraysize > 0){

total += *farray; // Add in value indicated by pointerfarray++; // Move pointer forwards through arrayarraysize--;

};return (total);

};

// end of file

43

Page 43: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

4.4 Principles of dynamic memory

Dynamic memory is usually referred to as the heap.

Pieces of memory are borrowed from the heap, rather like borrowing from a lending library. Pieces of memory can be borrowed on demand and should be handed back when no longer needed.

Failure to hand back memory to the heap is a leak. Programs that have memory leaks tend to grow to fill all available memory on the computer. (This is particularly dire for server programs; as these are expected to run for many months without a break).

Depending on the language: the programmer may or may not be required to manually hand back each piece of memory back to the heap. In C++: this is the responsibility of the programmer; whereas in Java there is a garbage collection mechanism.

Garbage collection involves an automatic spotting of pieces of heap memory that are no longer in use; and then recycling them.

Garbage collection appears to be a panacea in that memory leaks should not be possible; however there is also an associated loss of performance.

The heap is often implemented as a singly linked list. One implication of this is that if you allocate thousands of small pieces of memory then things can go very slowly due to a linear search for unused space.

44

Page 44: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

4.4.1 Objects on the heap

KEY FACTS

Objects work with pointers just as other types do.

As an object is created on the heap: the memory space is borrowed and a constructor is then invoked. The address of the new object is then supplied.

As an object on the heap is destroyed; a destructor is invoked and then the memory space is handed back to the heap

This involves two fresh keywords new and delete.

4.4.2 Arrays on the heap

KEY FACTS

Arrays of objects can be created on the heap.

As an array of objects is created on the heap: the memory space is borrowed and a constructor is then invoked on each member of the array. The address of the new array is then supplied.

As an object on the heap is destroyed; a destructor is invoked on each object and then the memory space is then handed back to the heap

An array borrowed all at once should be handed back all at once.

Borrowing memory from the heap for an array of objects: employee *myemp; // DECLARE POINTER

myemp = new employee [10]; // CREATE OBJECTS

Handing back an array of objects to the heap:delete [ ] myemp;

45

Page 45: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

4.5 The Destructor

The destructor is a special member function used to tidy up after an object as it is destroyed.

Object destruction involves invoking the destructor automatically.

A programmer can use the destructor to ensure that resources are handed back cleanly (e.g. related sub objects that need to also be deleted). Using a destructor to hand back related resources means reliability because it is automatic.

A class does not have to have a destructor; which is often OK.

You can only have one destructor for a class.

Declaring an object as a local variable invokes the constructor at the start of the function and the destructor at the end of the function.

Destructors should not have a return value specified.

Destructors have the same function name as the class they belong to with a preceding tilde (~).

46

Page 46: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture 5 Polymorphism

5.1 Some Definitions

Poly Literally means MANY (from the Greek).

Morph Literally means FORM or SHAPE (from the Greek).

Polymorphism Is concerned with something having many forms.

In the case of this lecture: polymorphism is referring to member functions which share the same name and purpose yet they are distinguished by their blend or parameters. The specific word for this is:

Overloading The use of the same (function) name for similar facilities.

5.2 Overloading Ordinary Functions

We are used to identifying which function is being called by its name; this is not the whole truth in C++.

The function name and the combination of parameters make up the signature that is used to identify which function is called. (The return type is not part of the signature).

In C++ using the same name for several functions is called function overloading.

We can (therefore) have a number of functions with the same name but different signatures. Each will have its own prototype and implementation.

Function overloading is often used where similar operations are carried out on data of different types or representations.

Function overloading is often used where default values can be derived if particular parameters are ""missing"". For example: when booking a lecturer for a tutorial; if the campus is not identified then it assumes the campus to be the one where the lecturers office is. Programmers like using this because there is far less to remember.

5.3 Defaulting Function Arguments

Overloading is a great tool for making an API (application programmer interface) easier to remember.

Using function overloading to deal with "missing" parameters that are defaulted to fixed values can be expressed more simply and briefly using default arguments.

47

Page 47: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

In this situation: the programmer provides a single prototype and implementation showing the values that can be defaulted. The one prototype is then used to cover the variations where parameters are defaulted.

Not all arguments for a function need to have default values defined.

All of the arguments which have default values defined must be at the end of the argument list.

These should be ranked with the argument least likely to be defaulted placed ahead of those more likely to be defaulted.

Argument subsets must be: in sequence, continuous and start from the left hand side. Expressed differently: the compiler is clever but not telepathic when deciphering defaulted arguments.

We can apply this technique to member functions in the exact same manner. Programmers like using this because there is far less to remember.

An Example of Defaulting Function Arguments

void BookMaternityAppt (int =0, char = ‘F’);

48

Page 48: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

5.4 Overloading Constructors

A constructor is called whenever an object is created; by whatever route and in whichever area of memory (heap, stack, etc). If no constructor is provided by the programmer; then memory will be provided anyway however the opportunity to ensure that it is initialised will have been lost.

We are familiar with the default constructor: it has no arguments. In the same way as functions and member functions can be overloaded: so can constructors. This means defining arguments for the constructor like any other function. Rather than constructing an object and then setting values on it: programmers mostly choose to use a constructor that sets the values immediately.

HINTSIt is good practice (essential) to have a default constructor for every class.

5.5 An Example of Overloading Constructors

class Classroom{private:

char campus[50];char room[50];float floorarea;

public:Classroom ( ); // DEFAULT CONSTRUCTORClassroom (char *acampus, char *aroom, float anarea);

};

Classroom::Classroom ( ){

strcpy (campus, "");strcpy (room, "");floorarea = 0.0;

}

Classroom::Classroom (char *acampus, char *aroom, float anarea);{

strcpy (campus, acampus);strcpy (room, aroom);if (anarea >= 0.0)

floorarea = anarea;else

floorarea = 0.0;}

49

Page 49: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture 6 Composition and Inheritance

6.1 Relationships "HAS-A" versus "IS-A"

A major objective of OOP is to do with the reuse of code. We achieve this through several techniques:

1) Composition involves a class having a member variable whose type is another class.

This is used to represent "HAS-A" relationships. For example: a Student class has an enrolment date of the Date class.

2) Inheritance involves creating a new (derived) class based on an existing (base) class. The derived class inherits most of its storage and behaviour from the base class.

This is used to represent "IS-A" relationships. For example: the creation of a PartTimeStudent class is derived from a Student class.

6.2 Composition in Practice

An object here is composed of member variables that are objects of other classes.

This is a natural progression from classes being abstract data types. Member variables can be declared with a type which is an existing class.

A class that is mostly composed of member variables that are objects of other classes may be referred to as a composite class or a composition class. A member variable that is an object may be referred to as a sub object.

Observe:Access to values within sub objects is via the public methods of the (sub object) class.

50

Page 50: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

6.3 Inheritance

What is inheritance ?Inheritance involves creating a new class that is a variant of an existing (base) class.

The new (derived) class inherits the member variables and functions from the base class. The derived class can have additional member variables and member functions. Derived class member functions can also override some of the inherited member functions where they have the same signature.

Example: Suppose that a class Student has already been designed and implemented and that a new

application needs a class GradStudent. Since a GradStudent is a Student (IS-A type), rather than build the class GradStudent from

scratch, we can add to the class Student whatever data and methods it needs to become a GradStudent.

For example, class GradStudent might need additional data members to describe particular departmental exams that only graduate students must take and pass, as well as methods to store and retrieve these data.

Class GradStudent is derived from class Student.

The resulting class GradStudent is said to be inherited from the class Student. The new class GradStudent is called a derived class or a subclass of Student. The original new class Student is called the base class of GradStudent. The derived class GradStudent inherits all of the data and methods from the existing class

Student (except for constructors, the destructor, and an overload of the assignment operator). A derived class thus has all of the data and methods (with the exceptions noted) of its base

class, in addition to added data and methods. Inheritance promotes code reuse because the code in the base class is inherited by the subclass

and thus need not be rewritten. Inheritance also provides a mechanism to express the natural relationships among the

components of a program.

51

Student

GradStudent

Page 51: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

6.4 Public, Private and Protected members

class Classname{

public: //Public membersprotected: // Protected membersprivate: //Private members

}

The public and private keywords were encountered early in this course of lectures as a way of enforcing encapsulation.

Within a class declaration a member can be marked public: this means it is visible and useable from outside the class.

Within a class declaration a member can be marked private: this means it is not visible or useable from outside the class. By default: members declared within a class declaration are private.

This can be summarised as follows:public members are accessible to everyone.private members are not available to anyone else - even classes derived from this one.

In developing derived classes where access is needed to all base class members: neither public nor private membership are ideal.

The protected keyword allows base class members to be inaccessible to all classes except for classes derived from the base class.

Using protected members allows the base class to have a measure of privacy whilst still permitting derived classes to have easy access.

52

Page 52: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

6.5 Public, Private and Protected Derivations

Derivation Type Base Class Member Access

Derived Class Access

private private inaccessiblepublic privateprotected Private

public private inaccessiblepublic publicprotected Protected

protected private inaccessiblepublic protectedprotected protected

A private derivation results in a derived class that has: Inherited private data members from the base class that are inaccessible in the derived

class. Inherited public members and protected members from the base class that are private

members in the derived class.

A public derivation results in a derived class that has: Inherited private data members from the base class that are inaccessible in the derived

class. Inherited public members from the base class that are public members in the derived

class. Inherited protected members from the base class that are protected members in the

derived class.

A protected derivation results in a derived class that has: Inherited private data members from the base class that are inaccessible in the derived

class. Inherited public members and protected members from the base class that are protected

members in the derived class.

53

Page 53: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Example of a protected member

#include <iostream.h>

class Student{private:

char Student_No[10];protected:

char Student_Name[50];public:

void output_summary () const;};

void Student::output_summary () const{

cout << Student_No << "\t" << Student_Name << endl;}

class PartTimeStudent : public Student{private:

char PTS_Days_On_Campus[7];public:

void output_summary () const;};

void PartTimeStudent::output_summary () const{

cout << Student_No << "\t"; // The compiler should complain here !cout << Student_Name << "\t";cout << PTS_Days_On_Campus << endl;

}

54

Page 54: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture 7 Object-oriented Design using UML

7.1 Design

7.1.1 Analysis ---- inquiry, examination, study

Program development may begin with a study, or analysis, of a problem. To determine what a program is to do, we must first understand the problem. If the problem is written down, we begin the analysis phase by simply reading the problem.

While analysing the problem, it proves helpful to name the pieces of the solution that store information.

Example 7.2.1: calculation the distance between two points

P1 P2

The unknown that represents the result could be appropriately named distance.

7.1.2 Design

Design refers to the set of activities including

(1) Defining an architecture for the program that satisfies the requirements,(2) specifying an algorithm for each program component in the architecture.

An algorithm is a step-by-step procedure for solving a probelem or accomplishing some end, especially by a computer. A good algorithm must

list the activities that need to be carried out list those activities in the proper order.

Example: an Algorithm to bake a cake :

(1) Preheat oven.(2) Grease pan.(3) Mix ingredient.(4) Place ingredient in cake pan.(5) Place cake pan in oven.(6) Remove cake pan form oven after 35 minutes.

7.2 Unified Modelling Language (UML)

The Unified Modelling Language (UML) is now the most widely used graphical representation scheme for modelling object-oriented systems. It has unified various notational schemes that existed in the late 1980s. The people who design systems use the language (in the form of graphical diagrams) to model their systems.

55

Page 55: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Some features of UML:

Was developed in mid-1990s, under the initial direction of a trio of software methologists: Grady Booch, James Rumbaugh and Ivar Jacobson.

UML is flexible. UML is extendable and is independent of the many OOAD (OO Analysis and Design)

processes. UML is a complex, feature-rich graphical language.

7.3 Use Case Diagram

When designing a project, it is rare to start with a detailed problem statement. Instead, software developers interview people who want to build the system, gather the information, compile a list of system requirements specify clearly what the system is supposed to do, design the system to specify clearly how the system should be constructed to do what is

needed.

The UML provides the use case diagram to facilitate the process of requirements gathering.

7.4 Use Case Diagram Example

7.4.1 Problem Statement

A company intends to build a two-floor office building and equip it with an elevator. The company wants you to develop an OO software simulator in C++ that models the operation of the elevator to determine whether or not it will meet their needs.

Figure 7.4 Use case Diagram for elevator system.

7.4.2 Identifying the Classes in a SystemAfter the problem is stated, the next step of OOD (Object-oriented Design) process is to identify the classes in the problem.Figure 7.4.2 lists the nones that perform important duties in the elevator system.

Building elevator clock scheduler person (person waiting on a floor, elvator’s passenger) floor (floor 1, floor 2) floor button

56

Move to other floor

Elevator System

Person

Page 56: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

elevator button bell light door

Figure 7.4.2. List of important nouns.

Based on these categories, the classes are likely to be them. Therefore, the model can be modelled based on these categories. The classes to be created are:

Elevator Clock Scheduler Person Floor Door Building FloorButton ElevatorButton Bell Light

7.4.3 Class Diagrams

7.4.4 Inheritance

7.4.5 Composition

57

Class name

data

methods

Elevator

currectFloor : int =1direction: enum = upcapacity : int = 1arrivalTime: intmoving: bool=false

+ summonElevator():void+ prepareToLeave(): void+ processTime(time: int):void+ personEnters():void+ personExits(): void

Button

FloorButton ElevatorButton

Page 57: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

7.5. Full elevator simulator class diagram

58

Building

Floor Elevator

Clock

Building

Scheduler

Person

Floor Elevator

Light FloorButton ElevatorButton Bell

Button Door

1

11 1

1

1

11

Services

passenger

waitingpassengers

Summons

Reference: H. M. Deitel and P. J. Deitel, C++ How to Program, 2/e. Prentice Hall, 1998. ISBN 0-13-

528910-6

Page 58: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture 8 Static Data Members and Methods, Static Binding and Dynamic Binding

8.1 Static Member Variables

Static member variables are created as the program starts and last for as long as the program runs. These variables are in the static area of memory.

A static member variable exists once per class (and not once per object like other member variables). Static member variables are effectively private global variables (but far more acceptable in their use). A static member variable can be accessed from all member functions (and elsewhere if declared as public – please don’t).

Static member variables are marked by the static keyword.

8.2 Static Member Functions

Static member functions are instance independent meaning not invoked on an object; and have no object as a context. Direct access to static member variables is allowed; but no access to member variables within a specific object is possible. (If necessary it must be handled via parameters).Static methods are marked by the static keyword.Excepted Code Showing Static Members

class Queue{private:

static int queues_constructed;static int queues_destructed;

public:Queue ( );static int live_queues ( );

};

int Queue::queues_constructed = 0;int Queue::queues_destructed = 0;

Queue::Queue ( ){

queues_constructed++;}

int Queue::live_queues ( ){

return (queues_constructed – queues_destructed);}

59

Page 59: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

8.3 Static binding

The binding referred to here is the binding of a function call to a particular coded implementation of the function.

Static binding (or "compile time binding") involves the function implementation being resolved (once and for all) whilst the program is being built (linked).

The process of static binding involves recognising a function by its signature (name, the number and pattern of arguments) and locating the corresponding implementation.

The alternative to static binding is dynamic binding (explained shortly).

Static binding is the default in C++ and has a performance advantage because it is done (completely) at compile time..

8.4 Dynamic binding

Again, the binding referred to here is the binding of a function call to a particular coded implementation of the function.

Dynamic binding (or "run time binding") involves the function implementation being resolved (each time) whilst the program is being run.

Dynamic binding involves identifying the class of the object in question using its signature and then locating the function implementation (via inheritance if necessary).

Dynamic binding can be applied to member functions of classes but not to ordinary functions.

The use of dynamic binding is indicated by the use of the virtual keyword.

Use of dynamic binding involves using a (base class) pointer to work with a mix of objects (each of a class derived from that same base class).

Each class has a table of virtual methods and a dynamically bound function call involves a lookup into this table. This table is the Virtual Method Table or vtable.

60

Page 60: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

8.5 An example of Dynamic Binding

This example involves a delivery company with a large fleet of vehicles (motorbikes and vans). The company needs to keep track of servicing and tax discs et cetera.

A class diagram for a delivery company.

61

Inheritance Relationship

Page 61: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Step 1

Firstly we define the class headers as per normal. The member function that will be dynamically bound is marked as virtual and appears with the same signature in each of the three classes.

// file: vehicle.h

#ifndef VEHICLE_H#define VEHICLE_H

class Vehicle{protected:

char LicensePlate[10];int ServiceInterval;

public:Vehicle ( );Vehicle (char *aplate, int aninterval);

virtual void output ( ); // shows license plate and service interval};

#endif// end of file

//file: van.h

#ifndef VAN_H#define VAN_H#include "vehicle.h"

class Van : public Vehicle{protected:

char refridgeration; // Y or N

public:Van (char *aplate, int aninterval, char afridge);

virtual void output ( ); // shows license plate and refridgeration};

#endif// end of file

62

Page 62: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

//file: bike.h

#ifndef BIKE_H#define BIKE_H#include "vehicle.h"

class Bike : public Vehicle{protected:

int NumOfPanniers;

public:Bike (char *aplate, int aninterval, char *panniers);

virtual void output (); // shows license plate and number of panniers};

#endif// end of file

Step 2

Having constructed the class headers; the class implementations (CPP files) can be coded. The implementations of dynamically bound member functions are not marked virtual and appear just as any other member function.

Step 3

Having constructed the class headers and implementations; it only remains to use the dynamic binding.

This is done by use of pointers to the base class (Vehicle). A pointer to a vehicle is permitted to point to a Vehicle, or a Van, or a Bike. After all, with the inheritant relationship in place: a van is a vehicle, a bike is a vehicle.

In our example program we use an array of vehicle pointers to keep track of a mixed fleet of vans and bikes. The example program then outputs details for every vehicle in the fleet. The details are output in each case according to the variety of vehicle in question.

63

Page 63: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

// file: vehprint.cpp

#include <iostream.h>#include "van.h"#include "bike.h"

void main ( ){Vehicle *group[4]; // array of pointers to Vehicles

// CREATE A MIX OF OBJECTSgroup[0]= new Van("L234ABC", 12000, "Y");

group[1]= new Bike("M345CDE”, 1500, 2);

group[2]= new Van("N456DEF", 6000, "N");

group[3]= new Bike("P567EFG", 2000, 0);

// OUTPUT THE MIXfor (int j=0; j<4; j++) {

group[j]->output( ); // dynamically bound call}

};// end of file

64

Page 64: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture 9 Advanced Techniques (1)

9.1 Inline Function

A criteria in the design of C and C++ as computer languages has always been high performance. As a result it has been used in operating systems and (time critical) control applications such as medical equipment and factory robots. Major applications such as word processors and database management software are also usually written in C++.

There is a performance overhead each time a function is called. Values are put on the stack to be passed to the sub function and again when a return value is passed back to the caller. For most functions the overhead is acceptable; however where functions are particularly small it would be preferable to use a copy of the sub function code rather than calling the sub function.

In C++ we can inline a function such that its code is inserted each time it is ""called"". This makes the program faster; though the executeable can often be larger.

With an inline function the implementation is defined in the definition; thus active code instructions appear in the header file.

There are limits to what can be inlined: loops (for, while, etc) cannot be used and will be rejected by the compiler.

This involves use of the inline keyword which suggests that the compiler inline the function but (unusually) does not force the compiler to do so.

#include <iostream.h>

inline int larger (int value1, int value2){return (value1 > value2 ? value1 : value2);}

void main ( ){int num1 = 50;int num2 = 500;

cout << larger (num1, num2) << endl;}

65

Page 65: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

9.2 Inline Member Functions

Member functions can also be inlined in the same way as ordinary functions.

// In the H file

class Video{

public:// OTHER MEMBER FUNCTIONSchar* get_name ( );

private:char* name;

};

// In the CPP file:

inline char* Video::get_name ( ){

return (name);}

66

Page 66: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

9.3 Implicit Inlining

Inline member functions can also be expressed as follows:

class Video{

public:// OTHER MEMBER FUNCTIONSchar* get_name ( ) { return (name); };

private:char* name;

};

This is a very convenient and concise way of expressing an inline function; and many commercial developers use it for that reason.

Notice, however that placing inlines in the class header breaks the purity of the abstraction in that it places parts of the implementation into the interface.

67

Page 67: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

9.4 Friendship in Principle

What ? There are times when we want to have member functions and member variables which are private; so far as the wider world are concerned, but available to a few specific functions or classes.

This is applicable when classes are written as a closely coupled group: for example "Doubly Linked List" and "List Element". In this situation publicly available member functions perform some (time consuming) validation. Direct access to member variables can be made available to trusted friend functions or classes; where the validation is not required.

Why ?One advantage is the ability to have capabilities generally private with specific exceptions.

Another advantage is quicker runtime performance: bypassing validation which is unnecessary in specific contexts.

How ?Friendship is granted by a class to any of the following:

An ordinary function A method of another class Another class (all its methods to be friends)

68

Page 68: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

9.5 Granting Friendship to an Ordinary Function

A function cannot declare itself as a friend to a class. Friendship is granted by the class.

The friend function is prototyped in the class granting a friendship. These usually appear in the public section of the class definition.

Friend functions do not have an object as context in the way that member functions do. Private member variables are accessible on objects passed by reference.

More than one class can grant friendship to a function. The friend declaration should appear in each class definition where friendship is granted.

This involves the use of the friend keyword.

HINTS

Having prototypes for friend functions declared in the class definitions makes such functions traceable.

class Video{

public:Video ( ); // CONSTRUCTORvoid set_all (char* = "", char* = "", int = 0);

friend void output (Video&);

private:char* name;char* producer;int quantity;

};

void output (Video& avideo){

cout << "Name of Video: " << avideo.name << endl;

}

69

Page 69: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

9.6 Granting Friendship to a Method of Another Class

A member function cannot declare itself as a friend to another class. Friendship is granted by the class to be accessed.

The friend member function is prototyped in the class granting a friendship. These usually appear in the public section of the class definition. Private member variables are accessible on objects (of the befriended class) passed by reference.

More than one class can grant friendship to a member function. The friend declaration should appear in each class definition where friendship is granted.

A forward declaration will be required because neither class can be completely defined without the other.

class Video; // FORWARD CLASS DECLARATION

class Customer{public:

// OTHER NECCESSARY MEMBERSint query (Video&);

private:char* name;char* address;

};

class Video{public:

// OTHER NECCESSARY MEMBERSfriend int Customer::query (Video&);

private:char* name;char* quantity;

};

int Customer::query (Video& avideo){

if (avideo.quantity > 0)return (1);

return (0);};

70

Page 70: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

9.7 Granting Friendship to Another Class

Friendship is granted by the class to be accessed.

Friendship is granted on a one way basis. Friendship is not reciprocal.

All the member functions of the friend class have direct access to private variables of the granting class.

Private member variables are accessible on objects (of the befriended class) passed by reference.

A forward declaration will be required because neither class can be completely defined without the other.

class Video; // FORWARD CLASS DECLARATION

class Customer{public:

// OTHER MEMBER FUNCTIONSint query (Video&);

private:char* name;char* address;

};

class Video{public:

// OTHER MEMBER FUNCTIONSfriend class Customer;

private:char* name;char* quantity;

};

71

Page 71: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture 10 Advanced Techniques (2)

10.1 Operator Overloading - in principle

Conceptually: the defining of a class is about the creation of an abstract data type which (usually) represents something or someone in the physical world.

It is possible in C++ to "hijack" the familiar operators for use by your class; such as +, - and so on.

A wide range of operators can be overloaded (hijacked) as including the following:the mathematical operators [++, --, +, -, *, /, etc],and the comparison operators [>, <, !=, etc],and the logic operators [&&, ||, etc],and the input/ output operators [>> and <<].

The overloaded operators can be used in the same way as an ordinary expression. The math rules (e.g. multiplication before addition) still apply.

Overloaded operators should be used to achieve the same or similar effect. Do not use them in counter intuitive ways.

Operator overloading is not a relevant facility for most classes, but, when it is appropriate it is excellent.

HINTSProfessional software engineers will often cut and paste the code for operator overloading because the syntax is peculiar.

Be aware that operators are overloaded one at a time, for example: overloading "!=" does not imply any implicit overloading of "==".

72

Page 72: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

10.2 Operator Overloading - the equality test

class Matrix{private:

float value[4][4];public:

Matrix ( );float getvalue (int x, int y);int operator== (Matrix& other);

};

float Matrix::getvalue (int x, int y){

return (value[x][y]);}

int Matrix::operator==(Matrix& other){

for (int j=0; j<4; j++) {

for (int k=0; k<4; k++){

if (other.getvalue(j, k) != value[j][k])return (0) ; // NOT EQUAL

}}return (1); // EQUALITY PROVEN

}

73

Page 73: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

10.3 Operator Overloading - assignment

class Matrix{private:

float value[4][4];public:

Matrix ( );float getvalue (int x, int y);

Matrix& operator= (Matrix& other); // OVERLOADING ASSIGNMENT

};

float Matrix::getvalue (int x, int y){

return (value[x][y]);}

Matrix& Matrix::operator=(Matrix& other){

for (int j=0; j<4; j++) {

for (int k=0; k<4; k++){

value[j][k] = other.getvalue(j, k);}

}return (*this); // RETURN THE OBJECT ITSELF

}

74

Page 74: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lecture 11 Templates (extra reading)

11.1 Function Templates

What are function templates ?

There are times where the same algorithms are applied to different data types or classes. One example of this might be statistical functions such as average.

C++ permits us to create templates and then apply these to each data type as necessary. This mechanism involves the compiler generating a separate copy of the code for each data type.

Why use function templates?

We could create separate copies of (say) an average function for each data type; however this means creating a fresh copy each time; which then needs to be maintained.

11.2 Example code without function templates

#include <iostream.h>

long average (long, long);double average (double, double);

void main ( ){long p1 = 10, p2 = 20, p3;double j1 = 3.8, j2 = 9.9, j3;

p3 = average (p1, p2);cout << "Long average " << p3 << endl;j3 = average (j1, j2);cout << "Double average " << j3 << endl;

}

long average (long num1, long num2) { return ((num1 + num2)/ 2); }

double average (double num1, double num2) { return ((num1 + num2)/ 2); }

75

Page 75: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

11.3 Creating a function template.

A function template is a blueprint or stencil for a data type. The compiler generates functions according to the template for each data type as required.

The function template is created once (only). It is then applied to data types (by the compiler) to create multiple functions. These functions differ only in the data types of the arguments being used.

// avg_temp.cpp

template <class T> T average ( T num1, T num2 )

{T avg;

avg = ( num1 + num2 ) / 2 ;return ( avg ) ;

}

The keyword template indicates the creation of a template.

The identifier T is replaced by whichever data type the template is applied to.

11.4 Using function templates.

Once a template is provided: the compiler will generate the actual functions needed on demand. On encountering a function call: the signature is inspected and a function is generated from the template if necessary.

#include <iostream.h>#include "avg_temp.cpp"

void main ( ){long p1 = 10, p2 = 20, p3;double j1 = 3.8, j2 = 9.9, j3;

p3 = average (p1, p2);cout << "Long average " << p3 << endl;j3 = average (j1, j2);cout << "Double average " << j3 << endl;

}

76

Page 76: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

11.5 Function templates with multiple data types

Templates can be based around more than one data type.

// avg_many.cpp

template <class T1, class T2> T1 average (T1 value_array[ ], T2 num_values)

{T1 avg ;T1 total = 0 ;int k ;

for (k = 0; k < num_values; k++){

avg += value_array [ k ] ;}avg = total / num_values ;return ( avg );

}

#include "avg_many.cpp"#include <iostream.h>

void main ( ){

long long_values[ ] = {475, 1935, 523, 898};float float_values[ ] = {3.2, 4.75, 57.0};long long_avg;float float_avg;

long_avg = average (long_values, 4);float_avg = average (float_values, 3);

cout << "Long average is :" << long_avg << endl;cout << "Float average is :" << float_avg << endl;

}

77

Page 77: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

11.6 Class Templates

There are times where the same data organisation and algorithms are applied to different data types or classes.

One example of this has been real time 3D graphics applications (like games, computer aided design or even virtual reality). A need for high speed has been met by choosing to store co-ordinates as long format integers rather than floating point values. In this case the data structures and algorithms remain the same in principle but the co-ordinate data type changes.

C++ allows us to create templates for classes. The template declaration incorporates both a class declaration and an "implementation".

// alist.h

#ifndef ALIST_H#define ALIST_H

const int SIZE = 50 ;

template < class T >class ArrayList{

public:ArrayList ( ) ; // constructorint find (T value) ;void add (T value) ;int remove (T value) ;

private:T list_items [SIZE] ;int num_items;

};#endif

78

Page 78: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

// alist.cpp#include <alist.h>

// TEMPLATE OF CONSTRUCTORtemplate <class T>

ArrayList<T> :: ArrayList ( ){

for (int k=0; k<SIZE; k++)list_items[k] = 0;

num_items = 0;}

template <class T>int ArrayList<T> :: find (T value){

for (int k=0; k<num_items; k++)if (value == list_items[k])

return 1; // ITEM FOUNDreturn 0; // ITEM NOT FOUND

}

template <class T>void ArrayList<T> :: add (T value){

list_items[num_items] = value;num_items++;

}

template <class T>int ArrayList<T> :: remove (T value){ int j, k;

for (k=0; k<num_items; k++)if ( list_items [ k ] == value){

for (j=k; j<(num_items-1); j++)list_items[ j ] = list_items [ j+1 ] ;

num_items--;return (1);

}return (0);

}

79

Page 79: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Example program using the class template#include "alist.cpp"#include <iostream.h>

void main ( ){

ArrayList<int> int_list;

int_list.add(10) ;int_list.add(15) ;int_list.add(20) ;

if (int_list.find (15))cout << "Value found." << endl;

elsecout << "Value NOT found." << endl;

ArrayList<char> char_list;

char_list.add('a') ;char_list.add('c') ;char_list.add('e') ;

if (char_list.find ('c'))cout << "Value found." << endl;

elsecout << "Value NOT found." << endl;

if (char_list.remove ('a'))cout << "Value deleted." << endl;

elsecout << "Value NOT deleted." << endl;

}

80

Page 80: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

11.7 Container Classes and the S.T.L.

A container class is designed to manage a variable sized collection of objects.

Container classes usually include methods such as: insert object (to the collection)remove object (from the collection)find object (within the collection)sort objects (within the collection)etc ....

Container classes reflect data structures such as:arraysqueuesstackslinked listshashtablesetc ....

Most modern compilers include a set of template libraries offering a range of data organisations to the programmer.

There is an industry standard C++ library of templates which is supported across many compilers and platforms. It is called the Standard Template Library ( S T L ).

Unfortunately the Borland compilers do not seem to include the STL however there are a collection of equivalent template classes.

N.B.It has been observed that programs written to make extensive use of templates tend to produce significantly larger executeables (this is often referred to as code bloat).

81

Page 81: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

4 Materials for Lectures

82

Page 82: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

5. Materials for Seminars

Seminar 1. Pre-Processors

1.1 Exercise:

1.1 Using an example to explain the differences between procedural programming and object-oriented programming.

1.2 define objects.

1.3The Debug Cycle

The following diagram of "The Cycle of Programming Activities" shows what a programmer does and how these activities follow each other.

If we consider each activity and how it can be speeded up: Editting the source code: could be speeded up by learning to touch type. Compiling the source code: is a purely software process which is open to careful optimisation

and/ or reorganisation. Running and debugging the executeable: speed at this stage is a reflection of how efficiently

your program achieves its objectives. Diagnosing and locating bugs is in practice limited by the speed and clarity of the programmers though processes.

83

Page 83: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

1.2 The phases of compilation

84

Page 84: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

85

Page 85: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

86

Page 86: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

1.3 The Role of the Preprocessor

The "preprocessor" is usually built into the compiler for performance reasons. The diagram of "The Separation of the Preprocessor from the Compiler" shows the

relationship of the preprocessor to the rest of the process. The preprocessor is purely a “text in - text out” facility which works on your program source

code before it gets to the compiler. The preprocessor picks up and obeys directives embedded in the programs you edit. Each directive is on a line by itself and begins with a ‘#’. The #include directive is used to include a copy of another text file into a compile. We can use it in two ways; firstly to include header files for system facilities such as:

#include <iostream.h> // The angular brackets instruct the //preprocessor to search for this file in the system directories that it knows about. The second way in which we use the #include directive is to include our own header files as

follows:#include "employee.h" //The quotes instruct the preprocessor to // search for

this file in your current working directory). Either way the preprocessor is including simple text and only simple text from another file; thus

these files can be viewed or even edited.

87

Page 87: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

88

Page 88: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Seminar 2. Exercises

89

Page 89: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

1. Identifying and correcting the errors for the following code which is Date class definition:

// date.hclass Date{

private:int day;int monthint year;

Date();int get_month()int get_day()int get_year()void set_all(int; int; int)

}

2. Fill the gap when the video program is running, put ??? In the box if uncertain:

Before Constructor After constructor

90

Video rental

Name

Producer

Quantity

Name

Producer

Quantity

Page 90: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Before set_all(…); after set_all(…);

3. Using an example to explain data encapsulation.

4. What is data encapsulation and why it is important in object orientation?

5. Write a C++ class for an airplane. The Airplane class should have three data members: type of airplane, current flying speed, and maximum flying speed. The class should have the flollowing methods: Airplane(); set_type(); Airplane() //default constructor set_type() set_current_speed() set_max_speed() get_type() get_current_speed() get_max_speed()

6. Define object, class, and instance.

7. Write a procedure program, a structure program, and an object-oriented program to calculate the area of rectangles.

91

Rental.set_all(“Titanic”, “Cameron co”, 30);

Name

Producer

Quantity

Name

Producer

Quantity

Page 91: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

7. Seminar 3 Exercises

1. Draw a diagram to show an interface for operating a TV and construct a class for the interface.

2. Using example in Exercise 1(TV) to explain data abstraction of class.

3. Using an example to explain data encapsulation.

4. What is data encapsulation and why it is important in OOP?

5. Write a class for Bank_Account:

Data members:name, account_number, balance,interest_rate.Member functions: Bank_account();

deposit();withdraw();calc_interest();get_name();get_account();get_balance();get_interest();set_all();

92

Page 92: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Seminar 4 Exercises

1. What is destructor and what is it used for?

2. Write a C++ program to manage your class schedule this semester. A Course class should be created including methods, overloading functions, constructors and a destructor. Five Course objects should be created in the main programme.

3. What is a pointer?

4. What is the return value of operator new?

6. Modify the following class definition to inlude at lease two constructors and to give the implementation details (.cpp file) of the two constructors.

class Bank_Account{private: char name[NAME_LEN]; char account_number[ACCT_LEN]; double balance; double interest_rate;public: Bank_Account(); void deposit(double); void withdraw(double); void calc_interest(); const char* get_name(); const char* get_account(); double get_balance(); double get_interest_rate(); void set_all(char*, char*, double, double);};

93

Page 93: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Seminar 5 Exercises

1. Modifying the following codes to achieve polymorphism, what is the method used?

class Employee{

private:char name[40];char address [40];int age;char gender;

public:Emplyee();void set_name(char *);void set_address(char *);void set_age(int);void set_gender(char);void print();

}

2. Why polymorphism is important in OO programming.

3. Explain and distinguish the use of function overloading and the use of default argument.

4. What are the advantages and disadvantages for using default function argument.

94

Page 94: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Seminar 6 Exercises

1. For each problem description, decide whether it would be better to use composition (has-a relationship) or inheritance (is-a relationship)

A college bookstore wants to maintain a list of the books required for the sections of courses offered this semester. Each section includes a course number, section number, instructor name and primary text.

You are writing a graphics program that requires you to draw and maintain information about the following shapes: circle, square, triangle and line.

You operate a small bookstore and sell various types of publication. You need to maintain information about books, magazines and newspapers.

You would like to write an appointment scheduler program. For each appointment, you need information about the person's name and the appointment's date and time.

2. Based on “Employee” class, create a derived class “staff” with department and job titles. The final program will print out the staff list in an alphabetical order of names.

3. What are Composition and Inheritance and what are they used for?

Seminar 7-10 Group Project Meeting1. using UML to descrobe2. Group allocation

Seminar 8-10 Group Project Meeting

Seminar 11 Group Project Presentation

95

Page 95: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Materials for Labs

Lab 1. Using C++ Builder to create projects

1. Copy all the programmes from

L drive : ‘2001-02 on Mdx-bg-halls\Sys\Lecturer’ directory: Cmt2050\week1 Copy all the directories into your own directory (desktop or H drive). In your H: dirve (you can find it when you open My-Computer icon), create (or find) a

directory called work. Create a sub-directory in work, called week1. Save (move) all your files to your H: drive, work/week1 directory.

2.Create a project called project1 which includes files

print.h, print.cpp, and printmain.cppand run the project.

3.Create a project called project2 which includes files area.h, area.cpp, and areamain.cpp

and run the project.

4.Create a project called project3 which includes files procedure.cpp

and run the project.

96

Page 96: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lab 2 Exercises In

L:\ 2001-02 on Mdx-bg-halls\Sys\Lecturer’ directory: Cmt2050\week2 Copy ‘video’ directory into your own space (H drive or Desktop) and run the

program. Copy ‘airplane’ directory into your own space and run the project.

2. course work 1 (short programming task 1 ), see page 12.

Lab 3 Exercises

1. In L:\ 2001-02 on Mdx-bg-halls\Sys\Lecturer’

directory: Cmt2050\week3

Copy ‘myvideo’ directory into your own space (H drive or Desktop) and run the program.

Copy ‘bank’ directory into your own space and run the project.

2. Course work 1 (page 12), Marking.

97

Page 97: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lab 4 Exercises 1. In

L:\ 2001-02 on Mdx-bg-halls\Sys\Lecturer’ directory: xiaohong\week4 Run all the sample programs in week 4 direcory.

2. Course Work 1 deadline, Marking.

3. Course work 2, see page 14.

98

Page 98: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lab 5 Exercises 1.

L:\ 2001-02 on Mdx-bg-halls\Sys\Lecturer’directory: Cmt2050\week5

Run all the sample programs in that directory.

2. Course work 2, see page 14.

Lab 6 Exercises 1. In

L:\ 2001-02 on Mdx-bg-halls\Sys\Lecturer’directory: Cmt2050\week6

Run all the sample programs.

Course work 2 Marking.

Lab 7 Exercises In

L:\ 2001-02 on Mdx-bg-halls\Sys\Lecturer’ directory: Cmt2050\week7 Run all the sample programs.

Course work 3, see page 16.

Lab 8 Exercises In

L:\ 2001-02 on Mdx-bg-halls\Sys\Lecturer’directory: Cmt2050\week8

Course Work 3 Marking

99

Page 99: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Lab 9 Exercises 1 In

L:\ 2001-02 on Mdx-bg-halls\Sys\Lecturer’directory: Cmt2050\week9

Run all the sample programs in that directory.

2. Individual Project ---- see page 18.

Lab 10 Exercises

Individual Project ---- see page 18.

Lab 11 Exercise

Individual Project ---- see page 18.

Lab 12 Exercise

Individual Project Marking

100

Page 100: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

6. Sample exam paper

MIDDLESEX UNIVERSITY

EXAMINATION PAPER

2000/2001 Semester 2May 2001

COM2050

Object-oriented Programming with C++

Time allowed: Two Hours

Total number of questions: Five questions

Instructions to candidates Answer any THREE questions

Materials provided: Program-file-listing supplement.

Equipment permitted: None.

Total number of pages: 6

No books, paper or electronic devices are permitted to be brought into the examination room other than those specified above.

Candidates are warned that illegible scripts will not be marked.

101

Page 101: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

ATTEMPT ANY THREE QUESTIONS

Each question carries 33 marks.

Question 1

a) Using an example to explain the concept of class and object in C++. [6 marks]

b) Name and define the four most important features of OO Programming.

[15 marks]

c) The following main program uses the Video class that is included in the programming files. Write out the output when it is executed. For each set_all function, write out the number of arguments that have been used.

#include <iostream.h>#include “video.h”int main(){

Video vid1; vid1.set_all();

vid1.print(); vid1.set_all("Titanic");

vid1.print(); vid1.set_all("Titanic", "Cameron Co."); vid1.print(); vid1.set_all("Titanic", "Cameron Co.", 56); vid1.print(); return 0;

}

[12 marks]

102

Page 102: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Question 2

a) Explain the concept of a class Constructors. [4 marks]

b) Declare a Course class (in the file course.h) to include at least 2 constructors. The Course class should have data members:

course_code (e.g. com2050) course_name (e.g. Object Oriented programming) [12 marks]

c) Explain the concept of pointer. [5 marks]

d) Re-write the Course class definition in Question 2(b )(in course.h) to declare course_name as a pointer type and give the implementation of the following function:

void set_all (char*, char*) [12 marks]

103

Page 103: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Question 3

a) Explain the concepts of composition and inheritance. [6 marks]

b) For each of the following situations, decide between composition and inheritance relationships: [6 marks]

A college bookstore wants to maintain a list of the books required for different sections of courses offered in a semester. Each section includes a course number, section number, instructor name and primary text. Write out the relationship between a course and a course number.

You operate a small bookstore and sell various types of publication. You need to maintain information about books, magazines and newspapers. Write out the relationship between a magazine and publication.

You would like to write an appointment scheduler program. For each appointment, you need information about the person's name and the appointment's date and time. Write out the relationship between an appointment and the appointment’s date.

c) Using the Video class, construct an Inventory class for listing all types of videos. Give the inventory.h file to include at least the following functions:

set_video_info()print_video_info()

and data members:

all_videos[200]num_video

[8 marks]

d) Give the implementation file (i.e., inventory.cpp file) for the above Inventory class.

[13 marks]

104

Page 104: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Question 4

a) Explain the importance of polymorphism in object-oriented programming.[6 marks]

b) Use an example to explain the differences between procedural programming and object-oriented programming.

[10 marks]c) Explain overloaded constructors and the differences between

overloaded constructors and overloaded functions.[8 marks]

d) Explain the following concepts:[9 marks]

Pre-processor Static data members

105

Page 105: Information systems 28 - unimi.ithomes.di.unimi.it/piuri/pages/didattica/SInformatici/mat/...  · Web viewImplement an object-oriented design with appropriate C++ features. ... design

Question 5

a) The following is an Email_info class which allows you to keep track of people to whom you have sent important e-mail messages. Explain how you would modify the get_message() method to ensure that a given message cannot be changed in any way. [10 marks]

class Email_info{

private: char name [40]; // the name of recipientchar e_mail_address[60]; //email address of recipientchar message [120]; // message to the recipient

public:Email();void set_all(char* , char*, char*);char * get_name();char * get_message();char * get_email_address();

};

b) In the above Email_info class , explain the features of the type of memory, i.e. storage, the message variable is using.

[4 marks]

c) If the length of a message is changeable, dynamic memory allocation should be used. Re-write the message declaration and write the implementation details of the set_all function to demonstrate your understanding of dynamic memory management.

[12 marks]

d) In the above Email_info class, modify the set_all function to achieve polymorphism and explain the method used.

[7 marks]

106