Chapter 2Chapter 2
DCS 5085DCS 5085
Introduction to C++ & Introduction to C++ & object modelsobject models
• Introduction to C++
• Algorithms.
• Top – down design.
• Design techniques: Procedural and Object Model.
• Four principles in object model.
• Software complexity.
• Classes and Objects.
• Messages and Methods
Overview – how to design software
• C++ systems generally consist of three parts:– A program-development environment– The language– C++ Standard Library
• C++ programs typically go through six phases to be executed. There are:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. execute
2.1 Basics of a typical C++ Environment
1. Edit• Accomplished with an editor program (part of IDE,
notepad)• Types a program with the editor and makes corrections
if necessary.• File extension .cpp or .c.
2. Preprocess• Performed before compiler convert the program to
machine code.• Includes other text files to be compiled and perform
various text replacements.(linraries, shortcuts)
3. Compile• Translate the C++ program into machine language
code. (object code)
4. Link• Links the object code with the code for the missing
functions (Standard libraries and Private libraries) to produce an executable image.
• If the program compiles and links correctly, an executable program is produced.
5. Load• Loader loads program to memory before execution.• Additional components from shared libraries that
support the program are also loaded.
6. Execute• Under the control of CPU, executes the program one
instruction at a time.
• When designing a program the problem has to be faced of deciding on suitable methods of solving the different partial problems of the whole program.
• A description of how a particular problem is solved – a computational method – is called an algorithm.
• An algorithm consists of a number of elementary operations and instructions about the order in which these operations should be carried out.
• Certain demands can be made of an algorithm:– It should solve the given problem.– It should be unambiguous.– If the problem has an end view, such as computing a
certain value, then the algorithm should terminate after a finite number of steps.
2.2 Algorithms
• Algorithms can be expressed in many different ways:
– Natural language• Pictures and symbols
– Formal language• Mathematic notations.
• Flow charts have also been popular.
• Here we are dealing with programming, so what is naturally of interest to us is that algorithms can expressed in programming languages.
x=1 2 3 . . . .+n, n>0
Example
Problem : Fire alarm system in MMU. It monitors all the rooms to check if the temperature is normal and if there is smoke. If there is a fire, it rings the alarm.
Solution :
1) check temperature/smoke monitor in room 1- is it above normal?
2) If NO, proceed to next room (until last room)3) If YES, sound alarm4) Repeat Process
Start
Is temperature or smoke above normal?
Is it last room?
Next Room
Sound Alarm
End
NO
NO
YES
YES
Start
Is temperature or smoke above normal?
Is it last room?
Next Room
Sound Alarm
End
NO
NO
YES
YES
objects
- if one of them changes, the others remain unaffected (new room, different alarm, new sensors)- objects can be used by other programs for other functions (alarm for security, temperature for environment control)
• Let look at an example. We shall describe an algorithm that shows how the sum 1+2+3…+ n can be evaluated, if n is a given whole number >0.
• I.e.
• Algorithm in natural language:
• Algorithm in C++ language:
x=1 2 3 . . . .+n, n>0
1.Set sum equal to 0 and the counter k equal to 1.2.Repeat the following steps until k is greater than n: Calculate the sum of sum and k and save the result in sum. Increase the value of k by 1.3.The result required is now the number is sum.
cin >> n;sum = 0;for (int k=1; k<=n; k++)
sum + = k;cout << sum;
• To describe a general algorithms the description method must be able to express the following three constructors:
• Sequence. A sequence is a series of steps that are carried out sequentially in the order in which they are written.
– 1. Put the side pieces in position.– 2. Screw the back piece onto the sides.– 3. Put the shelves into the frame.
• Selection. Selection means that one of two or more alternatives should be chosen.
– If t > 0 then the result is t, otherwise the result is –t.
• Iteration. Part of the algorithm should be capable of repetition, either for a defined number of times or until a certain condition has been met.
– Whisk the egg whites vigorously, until they become fluffy.
• When a complicated problem has to be solve, it is helpful to split it into smaller subproblems, which are then solved separately.
• The subproblems can then be split into further subproblems, and so on.
• This is a very important technique in algorithm and program construction and is known as top – down design.
• In this way, different parts of an algorithm can be refined until a level is reached where the solution become trivially simple.
2.3 Top Down Design
Is it last room?Remove Current Room from Room List
Is Room List empty?
Get Next Room and
send to system
Send “EMPTY” signal to system
NOYES
Sub-problem
• Algorithm– Description of how a particular problem is to be solved (a
calculation method).• The most important algorithm constructs
– Sequence – series of steps.– Selection – choice between alternative paths.– Iteration – repetition.
• Top-down design– Divide into subproblems.– Solve the subproblems one by one.– Divide the subproblems into further subproblems.– Continue in this way until all the subproblems are easily
solvable.
Summary
• 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 imperative (procedural) programming languages
Function 1
Function 2
Function 3Function 4
Procedure Model
2.4 Procedural Model
• Object Model
– Object oriented decomposition of a task.
– 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
2.4 Object Model
• Abstraction is a problem solving technique in which details are grouped into a single common concept.
• An abstraction denotes the essential characteristics of an object that distinguishes it from all other kinds of objects.
• An abstraction focuses on the outside view of an object, and so serves to separate an object’s essential behavior from its implementation.
Cat
Purrs when pleasedChases away ratsSpeaks “Meow”
Climbs walls and trees
Abstraction denotes essential behavior
Abstraction denotes characteristic
Polygon
Variables:
Coordinates
Border color
Fill Color
Methods:
draw( )
erase( )
fill( )
AbstractionAbstraction
2.5 Four principles of Object model- Abstraction
• Encapsulation is the technique of hiding information within a structure.
• Abstraction and encapsulation are complementary concepts.
• Abstraction focuses upon the outside view of an object, while encapsulation prevents clients from seeing its inside view where the behavior of abstraction is implemented.
Methods
Variables
An object's variables make up the center or nucleus of the object and the methods surround and usually hide the object's nucleus from other objects in the program.
2.5 Four principles of Object model- Encapsulation
• Modularity is the act of partitioning the problem into individual components to reduce its complexity.
• The source code for an object can be written and maintained independently of the source code for other objects.
• In traditional structured design, modularization is primarily concerned with the meaningful grouping of subprograms.
• In object-oriented design, modules serve as physical containers (packages) in which we declare the classes and objects of our logical design.
2.5 Four principles of Object model- Modularity
• Hierarchy is an organizational structure with components ranked into levels of subordinates according to some set of rules (such as class-subclass relationship).
• Allows for inheritance of objects
2.5 Four principles of Object model- Hierarchy
• The problems that we try to solve in software often involve elements of complexity.
• Based on the complexity of the program domain, we can broadly categorize programs into the following:
• Programming in the small:
– Small projects where the code is developed by either a single individual or a small group of programmers.
– A single individual can understand all aspects of the project.
– The major task is the design and development of algorithms.
2.6 Software Complexity
• Programming in the large:
– Large software systems where the code is developed by a large team of programmers.
– No individual knows all aspects of the project.
– The major task is the management of details and the communication of information between diverse portions of the project.
• Conventional programming techniques based on structured top-down design are ideally suited for programming in the small, where algorithms are the fundamental building blocks.
• Object-oriented programming languages, where class and the object are the basic building blocks, are particularly useful in programming in the large.
• While developing sizable software systems, each working group can be assigned separate software components which have independent set of responsibilities.
• Object oriented methodologies help in reducing interdependency among software components. Such components can be created and tested as independent units, in isolation from other portions of a software application.
• An object satisfies the following properties:– Every object is an instance of a class– Every object has a state, a behavior, and an identity.– All objects that are instances of the same class have the
same behavior.• State: The state of an object is the collection of all properties
of the object plus the current values of each of these properties.
• Behavior: The behavior of an object is completely defined by its actions. Behavior is how an object acts and reacts, in terms of its state changes and message passing.
• Identity: Identity is the property of an object (such as its name), which distinguishes it from all other objects.
2.7 Classes & Objects
Music_Group
--------------------members;musicType;country;play()dance()
: D12
--------------------members = 6;musicType = Rap;country = America;
play()dance()
: Beatles
--------------------members = 4;musicType = pop,rock;country = Britain;
play()dance()
: SpiceGirls
--------------------members = 5musicType = bad;country = America;;
play()dance()
Class
Object
Identity
State
Behaviour
• The behavior of objects is dictated by its class. All instances of the same class will behave in a similar fashion.
• Even though a class can be considered as a type, a class has a more operational meaning. A class is a template for object creation. A class also has hierarchical rules (inheritance) which are not found in types.
• 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.
• Note that a message is different from a procedure call in conventional languages.
2.7 Messages & Methods
play( ):
print (“Sing”);
“Sing”
D12.play( )
Message
Action
Output
Method
Request Receiver
: D12
--------------------members = 6;musicType = Rap;country = America;
play()dance()
• There are two important distinctions:– A message has a designated receiver. The receiver is
some object to which the message is sent. In a procedure call, there is no designated receiver.
– The interpretation of the message (that is, the method invoked to respond to the message) is dependent on the receiver and can vary with different receivers. For example, an object of ‘Music_Group’ will give an output “Sing” which is different from the output “Football” from an object of ‘Soccer_Group’ in response to the same message “play”.
• Methods of an object can share and manipulate the state of the object which is not accessible to the methods of a different object.
• In procedural language, a set of functions can also share and manipulate a set of global variables, but there is no concept of information hiding in such an implementation.
Code Class
- struct example- iteration
struct fluid
{
public:
char initial;
double temp, density, velocity;
};
Code Class >> struct
struct fluid
{
public:
char initial;
double temp, density, velocity;
};
Code Class >> struct
keywords
struct fluid
{
public:
char initial;
double temp, density, velocity;
};
Code Class >> struct
name of struct
struct fluid
{
public:
char initial;
double temp, density, velocity;
};
Code Class >> struct
data members
struct fluid
{
public:
char initial;
double temp, density, velocity;
};
Code Class >> struct
data type declaration for each member
Code Class >> struct
#include <iostream>using namespace std;
struct Fluid{
public:char initial;double temp, density, veloc;
};
struct Solid{
public:char initial;double temp, density, stiffness;
};
int main(){
Fluid oil, water;Solid steel2, steel6;
water.initial = 'W';water.temp = 28.6;water.density = 5.65;water.veloc = 138;
steel2.initial = 'S';steel2.temp = 22.6;steel2.density = 7785;steel2.stiffness = 200000;
steel6 = steel2;
cout << "Water information " << water.initial <<"\ntemp" << water.temp <<"\ndensity" << water.density<<"\nvelocity"<<water.veloc;}
Code Class >> struct
Code Class >> iteration
3 types
•for
•fixed number of cycles; based on determining number of cycles
•while
•as long as statement is true, repeat expression/function
•do-while
•perform function first, then check statement
1. Initialize variable acting as test expression
2. Evaluate the boolean test
3. If true execute statements within loop
4. Update the variable
5. Go back to step 2
Note: if no change to variable then infinite loop (never ends) is created
Code Class >> while loop >> steps
int i= 0, number = 1;while (number) { cout << “Please type a number. ”
<< “Type 0 (zero) to stop execution.\n”; cin >> number; i++; if (i > 50) break; }
Code Class >> while loop >> example
Code Class >> while loop >> example
initialize variables
int i= 0, number = 1;while (number) { cout << “Please type a number. ”
<< “Type 0 (zero) to stop execution.\n”; cin >> number; i++; if (i > 50) break; }
variable as expression, value other than zero tests true
int i= 0, number = 1;while (number) { cout << “Please type a number. ”
<< “Type 0 (zero) to stop execution.\n”; cin >> number; i++; if (i > 50) break; }
Code Class >> while loop >> example
int i= 0, number = 1;while (number) { cout << “Please type a number. ”
<< “Type 0 (zero) to stop execution.\n”; cin >> number; i++; if (i > 50) break; }
Code Class >> while loop >> example
loop body
int i= 0, number = 1;while (number) { cout << “Please type a number. ”
<< “Type 0 (zero) to stop execution.\n”; cin >> number; i++; if (i > 50) break; }
Code Class >> while loop >> example
statements that provideexit from loop
Code Class >> while loop >> example
example application :
1. if you need to keep collecting data from the user, until the user says stop2. if you need to keep checking a sensor for feedback/signal3. if you need to search through a collection of information, until you find a specific item
Code Class >> while loop >> steps
1. Used when you want to execute loop at least once
2. Loops on test being true and exits when test is false
do
{ statement1;
statement2;
… } while (expression);
do { cout << “\n enter an id number:”; cin >> id_num; } while ((id_num < 100) || (id_num>1999));
Code Class >> while loop >> example
perform function first
• Convenient for counter controlled loops
• Pre-tested loop
• Same behavior as while
– Set counter to initial value
– Test counter against terminating value
– Update counter to next value
• All done in for header statement
Code Class >> for loop
• Example: for (int i = 0; i < 10; i++)
cout << i;
• Initialization, testing and updating in same statement
• Semicolons required
• Braces optional if only one statement
Code Class >> for loop >> examples