Title: ECE 538 Object Oriented Concepts Session 1
1ECE 538 Object Oriented ConceptsSession 1
- Dr. John G. Weber
- John.Weber_at_notes.udayton.edu
- http//academic.udayton.edu/JohnWeber
2Introduction
- Purpose Apply Object Oriented Programming
Concepts to real-world problems - Approach Provide a realistic project to
illustrate the OOP concepts - Use Visual C
- Application in the area of real-time simulation
- Introduce OOP concepts through several iterations
of the project - Class
- Combined lecture and lab
- Initial classes will be lecture to review and
introduce concepts - Later classes will be mostly labs to implement
projects - Grading
- Midterm 25
- Final 25
- Project 40
- Homework 10
3Assignments
- WebCT
- All assignments will be posted on WebCT
- Submit Assignments through WebCT
- Due Dates
- Assignments are due at the date and time posted
- Late assignments will be accepted
- One point per day deducted for late assignments
- Assignments will be graded and returned via WebCT
4What is OOP?
- Basic concept is to build software systems using
objects - An object is a software entity
- Includes both data and functions that operate on
the data - Objects may closely correspond to real-world
entities - e.g. automobiles in a traffic control simulation,
electrical components in a circuit-design
program, countries in an economic model - Objects are not always physical entities
- e.g.tasks in a scheduling program, individual
accounts in a banking program - OOP is not a programming language
- Object oriented programs may be written in any
language - Object oriented programming languages support the
object paradigm
5A Short History Of Programming
- Programming has evolved over time
- Individual Artistic Programming
- Structured Programming
- Modular Programming
- Imperative Programming
- Object-Oriented Programming
6Individual Artistic Programming
- A program was written by a single individual
utilizing - individual creativity
- infamous goto
- spaghetti code
7Structured Programming
- Programs were structured according to three basic
control structures - sequential control
- conditionals
- repetitions
8Modular Programming
- Programs were constructed using modules
- Each module has public and private parts
- Public parts are visible to everyone
- Private parts are visible only within the module
- Either part can define variables, procedures,
functions, and data types
9Imperative Programming
- Programs are partitioned into subroutines
- Information is exchanged between partitions by
passing data into and out of them - Assumes that small programs and big programs
differ only in size.
10Object-Oriented Programming
- Utilizes the class/object abstraction
- Bundles data and procedure together in the form
of an object - Object communicate by passing messages
11A Short History Of Abstractions
- The abstractions used by programmers have grown
over time - Functions Procedures
- Modules
- Abstract Data Types
- Class/Objects
- These abstractions have allowed us to better
manage program complexity.
12Functions Procedures
- Functions allow tasks that are used in many
places to be collected into one place and reused - Procedures allow programmers to organize
repetitive tasks in one place
13Modules
- Each module has public and private parts
- Public parts are visible to everyone
- Private parts are visible only within the module
- Guidelines for using modules
- The designer of the module must provide the
intended users with all of the information needed
to use the module correctly, and nothing more. - The designer of the module must provide the
implementers with all of the information
necessary to code the module, and nothing more.
14Abstract Data Types
- Enables
- Extending a programming language by adding
programmer defined types - Make unlimited instances of the programmer
defined type - Makes available to other code a set of programmer
defined functions that are used to manipulate the
instance data - Protect the instance data associated with the type
15Classes/Objects
- Key Concepts
- Message Passing
- Generalization/Specialization
- Polymorphism
- Relationships
- Behaviors
- Rules
16Message Passing
- An action is initiated by a service request
(message) sent to the specific object
17Generalization/Specialization
- Allows classes to share the same code.
- A relationship among classes (rather than among
objects)
18Polymorphism
- Allows shared code to be tailored to the specific
class
19Relationship
- The mechanism by which objects know about each
other - Two basic types of relationships
- Associations
- A relationship among objects
- Aggregations
- An object is composed of other objects
20Behavior
- The services that an object provides
- Static Behavior
- This is behavior that is independent of the
current state of the object - Dynamic Behavior
- This is behavior that differs according to the
state of the object
21Rules
- A declarative mechanism for addressing the issues
of global control description and business rules
22Complex Systems
- A complex system that works is invariably found
to have evolved from a simple system that worked.
23Hierarchy of a Complex System
- Composed of interrelated subsystems
- Subsystems also composed of interrelated
subsystems - Continue this decomposition until level of
elementary components - .
- Definition of primitive components is relatively
arbitrary - Based on the discretion of the observer of the
system. - Complex System composed of few kinds of
subsystems - various combinations and arrangements.
- Intracomponent linkages generally stronger than
intercomponent linkages.
24Traditional Languages
- Procedure Oriented
- C, Pascal, FORTRAN, etc
- Each statement tells the computer to do something
- e.g. get input, add numbers, display output
- Assembly language is the basic procedural
language - Program is a sequential list of computer
instructions - Procedural languages group computer instructions
into higher order functions - e.g. sine, exp(x), sort, etc.
- More comprehensible to the programmer
- For larger programs, functions grouped into
modules (structured programming)
25Object-Oriented Languages
- Smalltalk
- Arguably the first (and purest) OOP language
- Ada
- C
- Java
26Major OOP Concepts
- Encapsulation
- Grouping of related ideas into one
unitreferenced by single name - OO Encapsulation packages operations and state
attributes into object type - State accessible only via object interface
- Information/implementation hiding
- Uses encapsulation to restrict visibility of
internal information/implementation - State Retention
- State is the set of values that the object
contains - State persists from invocation to invocation
- Object Identity
- Property by which object can be identified and
treated as distinct software entity
27Major OOP Concepts (Cont)
- Messages
- Vehicle for interobject communication
- Classes
- Stencil from which objects are created
(instantiated) - e.g. man is a class, Joe, John, etc are instances
of the class man - Inheritance (by B from A)
- Facility by which class B has inherently defined
upon it each of the attributes and operations of
class A. B inherits from A. - A is superclass of B and B is a subclass of A
- Polymorphism
- Single operation or attribute name may be defined
upon more than one class and may have different
implementations in each of those classes. - Genericity
- Ability of function or class to work on different
data types
28OOP Program Structure
- Consists of functions and classes
- Functions
- Codify solution procedures
- Consist of a header and a body enclosed in
- Classes
- Blueprint for objects
29Sample Program
//BasicProgram.cpp //A first program in
c //Include standard input/output
routines--include is a preprocessor
directive include ltiostreamgt //This program
has one c function called main //main returns
an integer and requires no arguments e.g. () int
main() //declare and initialize integers int
i 10, j 5 //use the console output
routine from the std I/O namespace
cout //syntax is namespaceobject //also use
the end line symbol endl from the std
namespace //cout is an object // the ltlt
operator (normally left shift) is overloaded to
mean put to stdcout ltlt "Welcome to ECE 538
OOP" ltltstdendl stdcout ltlt "i " ltlt i ltlt "
j " ltlt j ltlt stdendl stdcout ltlt "sum "
ltlt ij ltlt " difference " ltlt i - j ltlt
stdendl //return an integer when
finished return 0
30Elements of the Sample
- Comments
- Begin with //
- Can enclose multi-line comment in / /
- Preprocessor Directive
- include ltiostreamgt instruction to the compiler
- Function Header
- int main() type of return value (int), name
(main), arguments in () - Every program must have a main function
provides entry point to program - Function Body
- list of statements enclosed in braces
- cout is an object from C Standard Library
(reference with std prefix)
31Another Sample
- Factorial function
- //factorial_fcn.cpp
- //A function to compute the factorial of its
argument -- argument must be positive integer - int factorial(int n)
-
- //declare local variable ans
- int ans 1
- while (n gt 1)
-
- ans ans n
- n n-1
-
- return ans
-
32Testing the Factorial Function
//factorial_test.cpp //a test program for the
factorial function include ltiostreamgt //include
a function prototype so the compiler knows that
factorial has been declared int factorial (int
n) int main () //input a value for the
factorial computation stdcout ltlt "Enter a
positive integer n " //declare n as an integer
before it is used in a program statement int
n //use standard console input object stdcin
gtgt n //make sure n is greater than zero if (n
gt0) stdcout ltlt "factorial(" ltlt n ltlt ") "
//display answer ltlt factorial (n) ltlt
stdendl else stdcerr ltlt "factorial("
ltlt n ltlt ") undefined" ltlt stdendl return
1 return 0
33Conditional Statements
- If Statement
- if (condition)
- statement one
- else
- statement two
- Condition form
- Variable relational operator Variable or
constant - e.g. n gt m, n lt 0
- Relational operators in C
- gt Greater than
- lt Less than
- Equal to
- ! Not equal to
- gt Greater than or equal
- lt Less than or equal
34More Functions and I/O
- Three standard I/O channels
- Standard input stdcin reads from keyboard
- Standard output stdcout outputs to screen
- Standard error stdcerr outputs to screen
immediately - Stdcin, stdcout, and stdcerr are objects in
I/O stream class - Recall objects have data and functions (called
member functions) - Cin has member function get
- Accessed via notation object_name.member_function
e.g. cin.get - Cout has member function put cout.put which
outputs a character - Cout also has member function flush cout.flush
which empties output buffer
35Another ExampleFunction upper()
//function that converts a character to upper
case //uses test function isupper from system
header file ctype.h include ltctype.hgt char
upper (char c) if (islower (c) ) // if c is
lower caseislower() is a function from
ctype.h return toupper(c) /make it upper
casetoupper is a function from
ctype.h/ else return c //don't
change c
36Testing upper()
include ltiostreamgt // main routine to test
upper() function // use member functions of
standard input/output objects char upper
(char) //function prototype int main () char
c, uc while (stdcin.get(c) ! 0) //use cntl z
to exit uc upper(c) stdcout.put
(uc) stdcout.flush() return 0
37Character Representation
- Use single quote marks a
- Characters represented by 8 bit integer code
(ACSII) - Special functions use escape sequences
- e.g. Newline \n (see table 1.2)
- Cin and cout useful for input and output of other
types - e.g if c is a character, keyboard input and
console output will be in character code form - If c is an integer, input and output will be in
integer form
38More Basic C Constructs
- Looping
- While
- While (condition)
-
- statements
- .
- .
- .
-
- Tests condition at start of loop
- May not execute any of the statements
39While loop Demo
// while4.cpp // prints numbers raised to fourth
power include ltiostreamgt include ltiomanipgt
//for setw to set the width of the
output using namespace std int main()
int pow1 //power initially
1 int numb1 //numb goes
from 1 to ??? while( powlt10000 )
//loop while power lt 4 digits cout
ltlt setw(2) ltlt numb //display number
cout ltlt setw(5) ltlt pow ltlt endl //display
fourth power numb
//get ready for next power pow
numbnumbnumbnumb //calculate fourth
power cout ltlt endl return 0
40Looping (Cont)
- Do While
- Do
-
- statements
- .
- .
- .
- while (condition)
- Tests condition at end of loop
- Always executes the loop at least one time
41Do While Demo
// divdo.cpp // demonstrates DO loop include
ltiostreamgt using namespace std int main()
long dividend, divisor char ch do
//start of do loop
//do some
processing cout ltlt "Enter dividend " cin
gtgt dividend cout ltlt "Enter divisor "
cin gtgt divisor cout ltlt "Quotient is " ltlt
dividend / divisor cout ltlt ", remainder is
" ltlt dividend divisor cout ltlt "\nDo
another? (y/n) " //do it again? cin gtgt
ch while( ch ! 'n' )
//loop condition return 0
42Looping (Cont)
- For Loop
- for (initial statement, continuation condition,
increment expression) -
- statements
-
- Example
- for ( I 1, I lt max I )
- statements
-
- for () statements //infinite loop
43For Loop Demo
// fordemo.cpp // demonstrates simple FOR
loop include ltiostreamgt using namespace
std int main() int j
//define a loop variable for(j0 jlt15
j) //loop from 0 to 14, cout ltlt j
j ltlt " " //displaying the square of j
cout ltlt endl return 0
44Which Loop Construct to Use
- Your Choice
- Can make equivalent
- Guidelines
- Use while when you dont know how many times the
loop will be executed - Use while (condition) statements if you
dont want the loop to execute at least once - Use do statements while (condition) if you
want the loop to execute at least one time - Use for (initial statement, continuation
condition, increment expression) when you know in
advance how many times the loop should be executed
45Data Types
- Data must be declared prior to use
- e.g int var1 //declares var1 as an integer
- e.g. int var1 273 //declares var1 as integer
and assigns 273 as its intital value - Note
- A declaration introduces variable name and type
- A definition allocates memory for the variable
- The statement int var1 is both a declaration
and a definition - Names
- Upper and lower case letters, numbers 0 to 9, and
the underscore (_) - Names must begin with a letter or the _
- Cant use a C keyword as a variable name
- Data Types
- char, int, long, float, double, bool
- Constants
- Directive const indicates variable will not
change during program - e.g. const float PI 3.1415927 //floating
point constant
46Operators
- Arithmetic
- Note No built in exponentiation operator
47Operators (Cont)
48Operators (Cont)
49Enumerations
- User-defined, integer type
- enum name symbol1 intval1,
- symbol2 intval2,
-
-
- e.g enum FirstQuarterMonths Jan 1, Feb 2,
Mar 3 - Note enum FirstQuarterMonths Jan, Feb, Mar
is same as enum FirstQuarterMonths
Jan 0, Feb 1 Mar 2 - Also Note enum SecondQuarterMonths Apr 4,
May, Jun is the same as enum SecondQuarterMonths
Apr 4, May 5, Jun 6
50Arrays
- Composed of consecutive memory cells holding same
date type - e.g. int A5 declares an array of five
integers - Array indexing starts a 0
- Hence, A0, A1, A2, A3, and A4 are
elements of the above array - Character Arrays
- C uses an array of characters terminated by a
null character (\0) to hold a string - C provides a standard string type (class)
- Member functions to the string class provides
easy means of manipulating strings
51Example
//readLine.cpp / Function to read a line from
standard input, store the line in a character
array, and return the length of the
line. / include ltiostreamgt //defintion of
readline function int readline(char s, int
len) //s is character array and len is length
of s char c '\0' //define c as a null
character int i 0 len -- //decrement
length to leave room at the end while (i lt len
stdcin.get(c) c ! '\n') si
c if (c '\n') si c si
'\0' //string terminator return i // main
program to test readline int main() const int
SIZE 100 char lineSIZE int n while ((n
readline(line,SIZE))gt0) stdcout ltlt"n "
ltltnltlt "\t line " ltlt line ltlt
stdendl return 0
52Pointers
- Pointer is the memory address of an object, data
item, or function - Declare a pointer by preceding the variable name
with - e.g. int j //declares a pointer j to an
integer - Let k be an integer declared as follows
- int k 100 //declare k and initialize to 100
- int j //declare a pointer j to an integer
- j k //set j to point at k the operator
indicates the address of k - Array assignments must be made using pointers
53Iteration
- Method to repeat execution of a number of
statements in a program - Discussion of loops provided examples of
iterations - The break statement
- Allows early termination of a loop
- Control transfers to first statement after the
loop - Use to terminate a loop based on a test condition
- The continue statement
- Transfers control to end of loop bodythe test
condition in while constructs - Used to skip over computations based on a test
but to continue the iteration if the condition is
still true
54GOTO
- Generally avoid
- Overuse leads to spaghetti code
55Switch Statement
- Like a multiple goto
- e.g. switch (expression)
-
- case constant-expr1 statements
- case constant-expr2 statements
-
- default statements
-
- Case labels must be distinct
- Control transferred to case matching expression
- All cases after the matching case are executed
- Use break in each case to make this a multi-way
if statement
56Switch Example
// platters.cpp // demonstrates SWITCH
statement include ltiostreamgt using namespace
std int main() int speed
//turntable speed cout ltlt "\nEnter 33,
45, or 78 " cin gtgt speed
//user enters speed switch(speed)
//selection based on speed
case 33 //user entered 33
cout ltlt "LP album\n" break
case 45 //user entered
45 cout ltlt "Single selection\n"
break case 78
//user entered 78 cout ltlt "Obsolete
format\n" break default cout ltlt
"Error in Entry\n" break return
0
57Assignment 1
- Read Chapters 1 and 2
- Code and run each of the example programs in this
session (Do not hand in) - Problems due May 25
- Extend factorial test program to allow the user
to decide if he wants to compute another
factorial or quit. - Write a program to read characters from the
keyboard and display the ASCII value on the
consolecontinue to read input until cntl z is
entered - Problem 1.1 Page 16
- Problem 1.2 Page 16