Title: 46699 Objectoriented Programming www.andrew.cmu.educourse46699
146-699 Object-oriented Programmingwww.andrew.cmu
.edu/course/46-699/
- Ananda Guna
- May 17, 1999 - Lecture 1
guna_at_ cs.cmu.edu School of Computer
Science Carnegie Mellon University
2Administrivia
- Web page, schedule, text
- TAs Ramu Arunachalam(Pgh) and TBA (NYC)
- Due dates
- Final exam
- Recitation hours
- Software
- MSVC (5.0)
- Metrowerks Codewarrior
- Any other compiler e.g. Borland
- g
3C Language Background
- Designed on top of C
- C plus OOP features, hence the name C
- Implications
- Almost all of the C features still work
- Some features were simplified, notably the I/O
- Many people claim to program in C, but never
really use its OOP features - also called a
better C - Most compilers support C/C
- The challenge of learning C is in the paradigm
shift - Java is based on C
4Review
- Variables
- Data types
- Primitives int, double, float, char...
- Conditionals (if, if-else, switch)
- Repetition (for, while loops)
- General structure of a C program
- Functions
- Prototypes
- Arguments/parameters
- Call by value
5Review
- All variables must be declared before use
- Must specify the type of your variable
- Compiler allocates memory
- e.g. int count0 float num1 0.0, num2 0.0
- Always initialize your variables or they contain
garbage - Conditionals Used to control execution
- if
- if-else, nested if
- switch
6Conditionals
- if ( boolean condition true) if(( boolean
condition true) - statements if (boolean condition
true) - ...
-
-
- if ( boolean condition true) if ( boolean
condition true) - statements statement
- else else if (boolean condition true)
- statements statements
- else if (...)
- switch(varName) //int varName
- case 1 statements
- break // REQUIRED
- case 2,3,4 statements
- break // REQUIRED
- default debug statement
-
7Repetition
- Loops
- for Used when we know the iterations
- while We dont know the exact iterations, but
we - know the exit condition
- do while Executes the loop body at least once,
test is at the bottom - for ( i0 ilt MAX i)
- //loop body statements
-
- while (i lt MAX) // assume i is initialized
- //loop body statements //Be sure to update
loop control variable -
- do while
- //loop body statements // Be sure to update loop
control variable - while (i lt MAX)
8Functions
- Units or modules within a program
- Each performs a specific task
- Allow for cleaner programs, promote reuse.
- May be
- system-defined. E.g. the math library functions
- User defined tailored to the application
- Must be called or invoked to be executed
- Prototypes are optional if the function
implementations appear before the function call.
However, it is good style to use function
prototypes - Can pass arguments to each other
- Can return a value upon exit(Single return
functions)
9Scope of a variable
- The segment of the program where it can be seen
- A local variables scope is the block within
which it is declared plus any nested blocks - A global variables scope is the entire program
- Lifetime of variables
- Locals die upon exit of a function
- Globals are alive throughout the life of the
program - It is bad style to use global varibles. Why?
- Global constants are fine. Why?
- E.g. const int MAX 10 // same as define in C
10Passing Arguments/parameters
- Call by value
- A copy of the variable is passed
- Call by reference
- The address of the variable is passed
- The called function has direct access to the
variable - Arguments
- Must match in number
- Must match in type
- The names do not matter, what matters is the
order of the arguments, i.e. the first is mapped
to the first and so on
11Call by value example
- void print ( int x, float y)
- cout ltlt x ltlt ltlt y ltlt endl
-
- int
- main()
- int x 10
- float y 22.7
- print(x, y)
- return 0
-
- // What will be the output for print(y,x)?
10
22.7
10
22.7
12Call by reference example
- void swap ( int a, int b) // the addresses are
passed - int temp
- temp a
- a b // change a gt change x
- b temp // change b gt change y
- cout ltlt a ltlt ltlt b ltlt endl
-
- int
- main()
- int x 7
- int y 55
- swap(x, y) // Note NO is required here
unlike C - cout ltlt x ltlt ltlt y ltlt endl
- return 0
-
x
y
55
7
13Arrays
- Group/collection of memory cells
- Each cell must be of the same type
- Declaring an array in C
- const int MAX 30 // define in C
- float stocksPricesMAX
51.5
98.30
0 1
MAX - 1
- Subscript/index begins at zero -
stocksPrices0 is the first element - Every
element is of type float
14Passing arrays as arguments
- void multArray(float arr, int count)
- // no for array arguments - as in C
- int i
- for ( i 0 i lt count i)
- arri 10.2 // change to the original
array -
- return sum
- //multArray
- // function call
- multArray(arr, count) // assume arr has been
loaded - // count is the items in the array
- cout ltlt "\narr0 ltlt setiosflags(ios
fixedios showpoint) - ltlt setw(10) ltlt setprecision(2)ltlt arr0
- //output with two decimal places
- // need include ltiomanipgt
15const array arguments
- void multArray(const float arr, int count)
- // no for array arguments - as in C
- int i
- for ( i 0 i lt count i)
- arri 10.2 // change to the original
array -
- //multArray
- const means the function can use, but may not
change the array - The above will throw a compile error - at which
line? - Use const to protect against accidently changing
the array values - Printing the contents of an array
- Using the array to do some computation
16Input/output in C
- To read from the console cin
- cin gtgt varName // read into this variable
- cin gtgt varName1 gtgt varName2
- gtgt is called the stream extraction operator
- To print to the console
- cout ltlt varName // dump contents of varName
- cout ltlt varName1 ltlt varName2 ltlt endl
- cout ltlt varName1 varName2 ltlt \n
- ltlt is called the stream insertion operator
- endl end of line (newline plus flush the output
buffer) - Much simpler and cleaner than C!
- Sample program
17File I/O in C
- Sequential Access Files - input
- programmer must create/recognize structure
- ifstream infile(filename, iosin)
- if (!infile) cerrltltFile cannot be open
- exit(1)
- infile gtgt date gtgt maxprice gtgt minprice gtgt close
- File output
- ofstream outfile(filename, iosout)
- outfile ltlt varName1 ltlt varName2 ltlt endl
- if no file then a file is created
- ltlt is called the stream insertion operator
- gtgt is called the stream extraction operator
- Much simpler and cleaner than C!
18File I/O in C ctd...
- ifstream infile(infile.txt) is ok too
- ofstream outfile(outfile.out) is ok too
- In each case object constructor is called
- logical file physical file
- alternative style
- ofstream outfile
- outfile.open(filename,iosout)
- Reading a file of data to eof
- while (infilegtgtvar1gtgtvar2) process
- while (!infile.eof()) infilegtgtvar1gtgtvar2gtgt
19File I/O in C ctd...
- You may use include Openfile.h utility
- ifstream infile
- OpenFileForReading(Enter input file , infile)
- ofstream outfile
- OpenFileForWriting(Outfile ? , outfile)
- infile.close()
- outfile.close() // explicit close
- File stream is also destroyed upon leaving the
scope.
20Problem Solving Process
- Review
- Algorithm
- Top-down design, stepwise refinement
- Pseudocode
- Flow Chart
- Phases of software development
- Planning figuring out the problem specs
- Design the algorithm, use pseudocode etc
- Code Translate the design into C/Java syntax
- Code review Spell-check your code. Simulate
the compiler looking for syntax errors - Compile With a thorough code review, compile
time is small - Test/debug
21System Costs Hardware vs. Software
100
Software
PercentSystemCost
Hardware
1950
2000
Year
courtesy R.Pattis
22Motivation for Design before Coding
- Analogy Think about how you write a paper
- Problem Statement? Outline? Abstract? Fill in
details based on the outline? Refine
sections/paragraphs? How do you proof your paper?
Do you just type something and watch the
spell-checker or do you print it out and read it
for errors? - Your solution is only as good as your design
- Coding should be low priority compared to design
- If you take short cuts, you will end up spending
a lot more time on the program. - Bottom Line There is nothing mysterious about
coding!!!
23OOP Versus Non-OOP
- Procedural programming OOP
- - Identify tasks/sub-tasks - Design the
classes - - Write procedures - Design the methods
- - Procedures act upon data - Objects
communicate to solve - to solve the problem the problem
- - Start with verbs - Start with nouns
- - Data is secondary - Data is primary
24Problem Solving - OO Design
- Identify the objects
- Identify the operations
- Design the algorithm/decompose into smaller
chunks - E.g Compute the amount of tuition to be paid
- Name the objects
- credit hours
- cost per credit hour
- Other costs, such as student activity fee etc
- Any discounts
- Name the operations to be performed
- Addition, subtraction, multiplication
- Algorithm
25Key Elements of OOP
- Abstraction Focus on the important, ignore the
details - e.g. Driving a car
- The interface of the car is what the driver sees
on the outside, i.e. the dash board, the gas
pedal and so on. - The implementation is a detail, e.g. what
exactly happens when I step on the gas pedal. - Encapsulation Information hiding
- The details of an object are hidden.
- Users are not allowed to make changes to the
implementation. - If there is any change in the implementation, it
does not affect the users(clients) of the
interface. - E.g. A Stack Class has as its interface init,
push, pop. The implementation may be changed
from an array to a linked list
26Key Elements of OOP
- Inheritance
- Building upon what is already defined
- A class can inherit from another class much like
a child inherits from its parent - Polymorphism
- Greek for many shapes
- Same name for different things
- Two forms in OOP
- Overloading Functions with the same name
- Over-riding A child class redefining its
parents functions
27OOP Terminology
- Program objects cooperating to solve a problem
- Properties of an object
- State gt data gt nouns
- Operations gt behavior gt verbs
- Identity
28Object Examples
- Example 1 An electronic mailbox
- States full or empty
- Operations add, delete ...
- Identity any 2 mailboxes will be different
- e.g. hou and aj29 each have a mail box
- Example 2 traffic signal
29Object Components
- An object is composed of both data and
- Operations which can act upon the data
Operations
Data
In a C object Operations gt member
functions (methods) Data gt data members
30Classes
- Class
- A collection of related objects.
- Instance of a class object
- Factory with blueprints/instructions to build
gadgets - Objects the gadgets the factory makes.
- Example
- Class checkingaccount
- Objects minnieCheckacct, mickeyCheckacct
31Example OOP Design
- Problem write a program to simulate an ATM
- Data (nouns)
- Account name
- Account balance
- ...
- Operations /behavior(verbs)
- Deposit
- Withdraw
- Inquire balance
- ...
32Problem ( Elevator Control Problem)
- Simulation of an elevator control system. 20
floors , 4 elevators - 1. Identify the data objects
- 2. Identify the data operations
- 3. Solve the problem
- Read Chapter 6-7 (Dietel Text)
- Any questions Email guna_at_cs.cmu.edu