45
ECP 4206 ECP 4206 Object Oriented Programming Object Oriented Programming with C++ with C++ Lecturer/Tutor: Chan Mun Leong, Mohd Haris Lecturer/Tutor: Chan Mun Leong, Mohd Haris Lye Lye Email: Email: [email protected] , , [email protected] [email protected]

ECP 4206 Object Oriented Programming with C++ Lecturer/Tutor: Chan Mun Leong, Mohd Haris Lye Email: [email protected], [email protected] [email protected]

Embed Size (px)

Citation preview

ECP 4206 ECP 4206 Object Oriented Object Oriented

Programming with C++Programming with C++Lecturer/Tutor: Chan Mun Leong, Lecturer/Tutor: Chan Mun Leong, Mohd Haris LyeMohd Haris Lye

Email: Email: [email protected] , , [email protected]@mmu.edu.my

Useful websites

• Free online C++ book– http://www.steveheller.com/cppad/Output/dialogTOC.html

• Detail explanation of OOP concepts can be obtained here– http://web.engr.oregonstate.edu/~budd/Books/oopintro3e/info/Rea

dMe.html• Big C++ Book website: Downloadable chapter on

graphical programming http://bcs.wiley.com/he-bcs/Books?action=resource&bcsId=4731&itemId=0470383283&resourceId=15209

• http://www.cplusplus.com/doc/tutorial/• http://www.learncpp.com/

ECP 4206 ECP 4206 Object Oriented Object Oriented

Programming with C++Programming with C++

IntroductionIntroduction

Chapter 1Chapter 1

1st 2/11

OverviewOverview

• Introduction to Programming• Comparison of Programming

Paradigms• Algorithms Development• Top-down Design of a Program• Procedural vs. Object Oriented

Language• Fundamentals of Object Oriented

Design

1st 3/11

Introduction to ProgrammingIntroduction to Programming• What is programming ?

– The act of writing instructions to command computers to perform a certain task

• Type of programming languages– Machine languages

• Machine dependent• Consist of strings of codes

– Assembly languages• English-like abbreviations to represent elementary operations• An assembler is needed to translate them into machine language

– High-level languages• Everyday English & mathematical notations written as a single

statement to accomplish substantial tasks• A compiler is needed to translate them into machine language

1st 4/11

Comparison of Programming Comparison of Programming ParadigmsParadigms

• Traditional programming methodologyAlgorithms + Data Structures = Programs

Niklaus Wirth

• Traditional programming methodology– Normally in the form of

• Unstructured programming• Procedural programming

– Modular and top down approach

– Mostly focus on functionality • New programming methodology

– Object oriented programming– Focus on both data and functionality– Try to mimic problem solving in the real world.

• Use objects that work together to solve a problem

1st 5/11

Unstructured ProgrammingUnstructured Programming• The program consists of only one section, i.e., main

– “main” consists of a sequence of commands or statements which modify data which is global throughout the whole program

• Advantages:– Simple and easy to practice by novice programmer– Good for small program; no lengthy planning needed

• Disadvantages:– Repetition of code

• i.e. if the same statement sequence is needed at the different locations within the program, the sequence must be copied

– Cumbersome maintenance• i.e., when a certain statement is changed, all subsequent affected

statements must be adjusted accordingly

• This has lead to the idea of grouping these similar sequences into a function that can be called.

1st 6/11

Procedural ProgrammingProcedural Programming• The program partitions the list of tasks into smaller pieces,

called procedures• A “main” section serves as a coordinator responsible to

invoke and pass relevant data to a particular procedure (procedure/function call), the data is processed by the procedure. The resulting data is returned at the end of the procedure

1st 7/11

• Program consist of a sequence of procedures being called.

• It is also possible to have procedure that call another procedures (sub-procedures)

• Advantages:

– Programs can be written in more structured manner, which will minimize error

1st 8/11

Modular ProgrammingModular Programming• Also called Structural programming

• The big problem is divided into smaller subproblems that are solved independently. Each subproblem is tackled by a procedure (function)

• Procedures with common functionality are grouped together into modules

• Each module can interact through procedure calls

• Each module can have its own data. This allows each module to manage an internal state which is modified by calls to procedures of this module

1st 9/11

• Disadvantages:

– No data protection

– i.e., any external functions can access the members of module

– Explicit creation and destruction

– i.e., an integer variable is declared within a particular scope. Once you leave the scope the integer variable is lost. This is automatically created and destroyed

1st 10/11

Object Oriented Object Oriented ProgrammingProgramming

• In an object oriented environment:– Software is a collection of discrete objects with their data and

functions that model “Real World” objects– The object has its own predefined function/method and is

responsible for its own data.– Each object is assigned a responsibility/task to provide a set of

service to other objects. – Objects of the applications work in a cooperative manner. – Software problems mainly focused on “What these objects do”

rather than “How they do it”– All objects can be easily replaced, modified, and reused

• C++ is used in this course to practice OOP

1st 11/11

OverviewOverview

• Introduction to Programming• Comparison of Programming

Paradigms• Algorithms Development• Top-down Design of a Program• Procedural vs. Object Oriented

Language• Fundamentals of Object Oriented

Design

Program Structure

• Program = Data structure + Algorithm

• Data structure is a structured format used to represent the data so that it can be processed by the algorithm– E.g stack, linked list, queue

Algorithms DevelopmentAlgorithms Development

• A description of how a particular problem is solved by a computational method is called an algorithm

• An algorithm consists of a number of elementary operations and instructions and their order in which they are carried out

• An algorithm must fulfill the following demands:– It should solve the given problem– It should be unambiguous– It must be able to terminate within a finite number of

steps, with a possibly computed end value

2nd 1/9

• Algorithms can be expressed in many different ways:

– Natural language

• Words, pictures and symbols

– Formal language

• Mathematic notations

• Flow charts

2nd 2/9

• A typical algorithm must be able to be expressed in one or more of the following three constructs:– Sequence: A series of steps that are carried out sequentially in the order in

which they are written• Naturally built-in to most programming languages

– Selection: Selection means that one of two or more alternatives should be chosen

• E.g., if, if-else, switch– Iteration: Part of the algorithm should be capable of being repeated, either

for a defined number of times or until a certain condition has been met• E.g., for, while, do-while

• A typical algorithm normally undergoes several stages of refinement (test and modified) before it becomes reasonably stable in performance

2nd 3/9

Top–Down Design of A ProgramTop–Down Design of A Program

• Top-down design: a very important technique in algorithm and program construction

• When a complicated problem has to be solved, it is helpful to split it into smaller sub-problems, which are then solved separately, i.e., divide-and-conquer

• The sub-problems can then be split into further sub-problems (if necessary), and so on

• Different parts of an algorithm can be refined until a level is reached where the solution become trivially simple.

• The trivial problem is then solved by implementing the function.

2nd 4/9

Top-Down Approach(Example)

• Write a program to check if a 9x9 grid is a sudoku solution

• Iteration 1

1. Get the input

2. Check the various constraints:

3. Write output.

Top-Down Approach(Example)

• Write a program to check if a 9x9 grid is a sudoku solution

• Iteration 2 1. Get the input 2. Check the various constraints:

– 2a. Check rows.– 2b. Check columns.– 2c. Check 3x3 squares.

3. Write output.

• Procedural Model

– The task to be performed is decomposed into sub-tasks, until the sub-tasks are simple enough to be implemented directly

– Tasks are modeled as procedures or functions in traditional procedural programming languages

– Program consist of these functions being executed sequentially

Function 1

Function 2

Function 3Function 4

Procedural Model

2nd 5/9

• Object Model

– Object model is the conceptual framework of any object oriented system

– An object model encompasses the following four principles:

• Abstraction

• Encapsulation

• Modularity

• Hierarchy

Object Model

2nd 6/9

Procedural vs. Object Procedural vs. Object Oriented DesignOriented Design

Procedural design• You create a program by determining:

– The sequence of tasks you want your program to accomplish

– Then figuring out the steps or procedures that are needed to accomplish the task

– Consider the data to be processed by the procedure

– The code is organized into several functions, and each function typically represents a sub-task.

– The program is typically modeled with a data flow diagram

2nd 7/9

DFD Diagram for Student Registration System

Procedural vs. Object Oriented Procedural vs. Object Oriented DesignDesign

• In object oriented design You create a program by determining:

• First, what type of objects the program needs to accomplish its goal

• Each object has a list of responsibility and service that it provide to other object.

• To provide this service , the objects has their own data and the related members function

2nd 7/9

In a library system you have the following objects

Book, Inventory, Librarian, Loan ,

Procedural vs. Object Oriented Procedural vs. Object Oriented DesignDesign

• In object oriented design, ensure that it can provide the services provided

• For each kind of object, you determine what information (attribute) the object needs to contain, and what operation (method) the object can perform.

• Asking the object to activate its operation can also be viewed as sending a Message to the object to perform the operation.

• The program is then developed by creating the objects and invoking the object’s method.

2nd 7/9

Procedural Design ExampleProcedural Design Example• Design a software that control a robot to cook an

instant noodle.makeNoodle(){ heatedWater = boil(water);Add(noodle, heatedWater);Mix(noodle, flavoring);Cool(noodle);Return noodle;}

// Take note that the focus of the program is on designing series of procedure that need to be performed . The procedure will process the data (noodle,water) to get the final output (cooked noodle)

2nd 7/9

Main()

{ // Call the function

cookedNoodle=makeNoodle();

}

OOP ExampleOOP Example

// Take note that the focus of the program in on designing objects. Then ask

the object to do the job by sending message to them.

2nd 7/9

Main()

{ // Create the controller and noodle object

ControllerClass controller; Human human123

NoodleClass myNoodle;

// Send a message to the controller , requesting it to do the job

// The main function do not need to know how the noodle is made but only what the controller can do (abstraction).

Controller.makeNoodle(myNoodle);

human123.eat(myNoodle);

}

OOP ExampleOOP ExamplemakeNoodle(noodle){water.boil(); // ask the water object to boil itself.noodle.add(water); // ask the noodle object to add the boiled water to itselfnoodle.mix(flavoring); // ask the noodle object to mix itself with the flavoring object.noodle.cool(); // ask the noodle object to cool down}

//OOP approach in program design is like organizing a party. You assemble a group of members (objects), assign responsibilities to the members. Then activate them to do the job.

// The main organizer just coordinate the work done by these “cooperative objects”

2nd 7/9

OverviewOverview

• Introduction to Programming• Comparison of Programming

Paradigms• Algorithms Development• Top-down Design of a Program• Procedural vs. Object Oriented

Language• Fundamentals of Object Oriented

Design

Fundamental of Object Oriented Fundamental of Object Oriented DesignDesign

Object oriented design involve the following

concepts – Classes

• Similar to structure but can include members function

– Objects• Instance of the Class

– Data Abstraction and Encapsulation

– Composition

– Generalization and Inheritance

– Polymorphism

– Message Communication

3rd 1/10

ObjectObject• Object is the the basic run-time entities in an object

oriented system. – In C++ object is created by typing the class name followed by the

object name e.g Person tom;• Object is a complex variable that consist of the variable for

attribute (data) and method to manipulate the data– Compare this with simple variable ( int x, char option)

• Example: Person is class name , tom is the class instance or better known as object

3rd 2/10

Height = 165Weight = 70Gender = maleName = Tom Hanks

getGender(…)setHeight(…)calcBMI()

Person tom

Attributes of the object

Methods of the object

Interacting with Objects: Interacting with Objects: Client Server ParadigmClient Server Paradigm

• Objects interact in a client server environment

• The server object provide a set of services through the set of interface member functions

• The client request for a particular service by sending a request message to the server – This is done by: Client call the server members

function

3rd 2/10

Interacting with ObjectsInteracting with Objects• Objects interact by sending messages to one another• Object A (client) send message to Object tom (server) by

calling the method of Object tom.– In this case: tom is the server object (provide service to

Object A)• Object A as the client only need to know type of message

accepted and the type of response returned by an object’s method.

• In C++ tom.getGender() ;// send getGender() message to tom• Example:

– Objects: Customer and Account– Customer object may send a message to the account object

requesting for the bank balance

3rd 2/10

• Software object and real world object show similar properties: It has State and Behavior

• Software object:– Two characteristics: State and Behavior– State: what information/data it contains,

• Defined by the attribute value

– Behavior: what it can do• i.e., defined by the methods

3rd 3/10

ObjectObject

• Object of the same type differ by the value of the attribute

• Person p1, p2 // C++ code declare 2 object p1,p2

of type Person

3rd 4/10

Height = 165Weight = 70Gender = maleName = Tom

getName(…)getGender(…)

Person p2

Height = 100Weight = 50Gender = femaleName = Mary

getName(…)getGender(…)

Person p1

ClassesClasses• A class is a blueprint/template used to create object

– Person p1, p2 // Person is class name p1, p2 is object name

• A class contains all the information (data and methods) a typical object should have, i.e., a class is an abstraction of a software entity– E.g Person, BankAccount, Button, WindowsFrame

• Once a class has been defined, we can create any number of objects belonging to this class. – Person ali ; Button okButton ;

• When you create an object of a class (create an instance of a class), the object gets its state initialized

• Classes are user defined data types and behave like the build-in types of a programming language e.g int, char, float.

3rd 4/10

Class and ObjectClass and Object

• Following is an example of a class and its instance (object)

VariablesHeightWeightGender name

MethodsgetName(…)getGender(…)

Height = 165Weight = 70Gender = maleName = Tom

MethodsgetName(…)getGender(…)

class Person Object p of the class Person

3rd 5/10

Design Strategies InObject-Oriented Programming

• Abstraction– Representing an entity only with its essential attribute and operation– Encapsulation: Hide the detail information and implementation to simplify its

representation• Separation

– Separate what the entity does from how it does it.

• Composition– Build complex system by assembling the simpler part together . – This is done by the method of

• Association (outsource the job to other object, model the use relationship)• E.g computer use a memory to store data• Aggregation ( model the has a relationship eg. a car has an engine)

• Generalization – Find similar classes and group them under a single general class together– Promote reuse– Generalization can be achieved using

• Hierarchy • Genericity• Polymorphism

Design Strategies InObject-Oriented Programming

• The diagram here shows how the object oriented software structures is used to implement the design strategies in order to achieve the desired software engineering goals.

Data Abstraction and Data Abstraction and EncapsulationEncapsulation

• Abstraction = simplified representation of the entity in a software system

• It refers to the act of representing the entity with only the essential features without including the unnecessary details

3rd 6/10

Method:(Interface function)

calcCommision()

getName()

Data Abstraction and Data Abstraction and EncapsulationEncapsulation

• Abstraction is implemented by using Class • Classes use list of attributes such as size, weight

and cost, and functions to operate on these attributes

• Class is known as Abstract Data Types (ADT) because it implement abstract data type

• Packaging an object’s variables within the protective custody of its methods is call encapsulation

• Encapsulation is used to hide implementation details– Only the interface member functions are exposed

3rd 6/10

InheritanceInheritance• Inheritance is the process by which objects of one class

acquire the properties of objects of another class

• The base class (super class) represents the generalized model of objects you are dealing with

• The derived classes (sub classes) represent specialized objects constructed by customizing the base class for a specific purpose

• Each derived class shares common characteristics depending on the base class from which it is derived– i.e., cats and dogs are subclasses of a superclass called animals

– Cats and Dogs are derived class and Animal is base class

• The concept of inheritance provides the idea of reusability

3rd 7/10

PolymorphismPolymorphism• Polymorphism means the ability to takes more

than one form• An operation may exhibit different behavior in

different instances• The behavior depend upon the types of object that

invoke the operation (method)– Cat->sound() dog->sound() – // the function output is different depending on the

object type • Polymorphism is made possible with Dynamic

binding, where the code associated with a given procedure call is not known until the time of the call at run-time

3rd 8/10

Message CommunicationMessage Communication

• An object-oriented program consists of a set of objects that communicate with each other

• The process of programming in an object-oriented language therefore involves the following basic steps :– Creating classes that define objects and their behavior– Creating objects from the class – Establishing communication among objects

• Objects communicate with one another by sending and receiving messages much the same way as people pass messages to one another

• The concept of message passing makes it easier to build software system that directly model or simulate their real-world counterparts

3rd 9/10

Messages and MethodsMessages and Methods

• Action is initiated in object-oriented programming by a transmission of a message to an object responsible for the action

• The message is nothing but a request for an action, accompanied by any additional information (arguments) needed to carry out the request

• The receiver is the object to whom the message is sent. In response to the message, the receiver will perform some method to satisfy the request

• Behavior of an object is the total set of actions an object can perform

3rd 10/10