Introduction to OOP Why use OOP?
Object Oriented Programming (OOP) is one of the most
● Object Oriented Programming (OOP) is one of the most
●
widely used programming paradigm widely used programming paradigm
Why is it extensively used?
● Why is it extensively used?
●
● Well suited for building trivial and complex applications ● Well suited for building trivial and complex applications
● Allows re-use of code thereby increasing productivity ● Allows re-use of code thereby increasing productivity
● New features can be easily built into the existing code ● New features can be easily built into the existing code
● Reduced production cost and maintenance cost ● Reduced production cost and maintenance cost
Common programming languages used for OOP include
● Common programming languages used for OOP include
●
C++, Java, and C# C++, Java, and C#
Building Blocks of OOP: Objects & Classes Building Blocks of OOP: Objects & Classes
●Object: models a
● Real world object (ex. computer, book, box)
● Concept (ex. meeting, interview)
● Class has
● Process (ex. sorting a stack of papers or comparing two ● Set of attributes or properties that describes every object
computers to measure their performance) ● Set of behavior or actions that every object can perform
●Class: prototype or blueprint from which objects are ● Object has
● Set of data (value for each of its attribute)
created ● Set of actions that it can perform
● An identity
● Every object belongs to a class
Another Real World Example..
Real World Example of Objects & Classes
Object: FordCar1
Object: Person1
Attributes Behavior
Color: Yellow Start, Accelerate,
Reverse, Stop Class: Person Attributes Behavior
Class: FordCar Type: Coupe
Name: Ann Speak,
Model: Mustang
Attributes Listen, Eat,
Attributes Cylinder: 6 Height: 5’ 4”
Run, Walk
Name, Height, Age Age: 21
Color, Type, Model, Cylinder
Behavior
Behavior
Speak, Listen, Eat, Run, Walk Object: Person2
Start, Accelerate, Reverse, Stop
Object: FordCar2
Attributes Behavior
Attributes Behavior
Name: Adam Speak,
Color: Orange Start, Accelerate, Listen, Eat,
Reverse, Stop Height: 5’ 9”
Type: Coupe Run, Walk
Age: 24
Model: Focus
Cylinder: 4
1
Class Class ShippingBox
●A class is a set of variables (to represent its attributes) and
functions (to describe its behavior) that act on its variables
sender_name : string
receiver_name : string
cost_per_pound : int int shipping_cost() {
weight : int return cost_per_pound*weight;
}
shipping_cost() : int
Object Objects of ShippingBox class
●Object is an instance of a class that holds data (values) in Object BoxA
its variables. Data can be accessed by its functions sender_name = Julie
receiver_name = Jill
cost_per_pound = 2
weight = 5
shipping_cost()
Class
ShippingBox
Object BoxB
sender_name = Jim
receiver_name = John
cost_per_pound = 5
weight = 10
shipping_cost()
What is OOP? Problem Solving in OOP
Paradigm for problem solving by interaction among objects
● Problem: Ann wants to start her car
It follows a natural way of solving problems
●
● Ex. Ann wants to start her car
Object Ann Object Ann’s car
(1) Ann walks to her car
Name = Ann Color = Yellow
(2) Ann sends a message to the car to start by turning on the ignition Age = 21 Type = Coupe
(3)The car starts Speak() Model = Mustang
Run() Cylinder = 6
Walk() Start()
Accelerate()
Stop()
2
Abstraction Abstraction
●Extracting essential properties and behavior of an entity
●Class represents such an abstraction and is commonly
referred to as an abstract data type
Shipping Box Abstraction Class
Attributes sender_name : string
Sender’s name, receiver_name : string
Receiver’s name, cost_per_pound : int
Cost of shipping per pound, weight : int
Ex. In an application that computes the shipping cost of a Weight
box, we extract its properties: cost_per_pound, weight and Behavior shipping_cost() : int
its behavior: shipping_cost() Calculate shipping cost
Encapsulation
Inheritance
●Mechanism by which we combine data and the functions
that manipulate the data into one unit ●Create new classes (derived classes) from existing
classes (base classes)
●Objects & Classes enforce encapsulation
●The derived class inherits the variables and functions of
the base class and adds additional ones!
●Provides the ability to re-use existing code
sender_name
receiver_name
cost_per_pound
weight
shipping_cost()
Inheritance Example Inheritance Example
BankAccount CheckingAccount SavingsAccount BankAccount
customer_name : string
customer_name : string customer_name : string customer_name : string account_type : string
account_type : string account_type : string account_type : string balance : int
balance : int balance : int balance : int
insufficient_funds_fee : int interest_rate : int deposit() : int
withdrawal() : int
deposit() : int deposit() : int deposit() : int
withdrawal() : int withdrawal() : int withdrawal() : int CheckingAccount SavingsAccount
process_deposit() : int calculate_interest() : int
insufficient_funds_fee : int interest_rate : int
process_deposit() : int calculate_interest() : int
3
20
Disadvantages of OOP 11.1 Recursion
• Recursive functions
●Initial extra effort needed in accurately modeling the – Are functions that calls themselves
classes and sub-classes for a problem – Can only solve a base case
●Suited for modeling certain real world problems as – If not base case, the function breaks the problem into a
opposed to some others slightly smaller, slightly simpler, problem that resembles the
original problem and
• Launches a new copy of itself to work on the smaller problem,
slowly converging towards the base case
• Makes a call to itself inside the return statement
– Eventually the base case gets solved and then that value
works its way back up to solve the whole problem
21 22
11.1 Recursion
• Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
– Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
– Base case (1! = 0! = 1)
23 24
1 // Fig. 11.1: fig06_29.cpp Outline
2 // Testing the recursive factorial function.
3 #include <iostream>
4 using std::cout; Only the base cases return values. 1. Function prototype
5 using std::endl;
6 All other cases call the factorial
7 #include <iomanip>
8 using std::setw;
function again.
9
1.1 Initialize variables
10 unsigned long factorial( unsigned long ); // function prototype
11
12 int main()
13 {
2. Input an integer
14 // calculate the factorials of 0 through 10
15 for ( int counter = 0; counter <= 10; counter++ )
16 cout << setw( 2 ) << counter << "! = " << factorial( counter ) 2.1 Call function
17 << endl;
1819 return 0; // indicates successful termination factorial
20 } // end main
21
22 // recursive definition of function factorial
23 unsigned long factorial( unsigned long number ) 2.2 Output results.
24 {
25 if ( number <= 1 ) // test for base case
26
27
return 1; // base cases: 0! = 1 and 1! = 1
else // recursion step
11. Define factorial
28 return number * factorial( number - 1 ); recursively
29 } // end function factorial
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
4
25 26
11.2 Recursion vs. Iteration 11.3 Inline Functions
• Repetition • inline functions
– Iteration: explicit loop – Reduce function-call overhead
– Recursion: repeated function calls – Asks the compiler to copy code into program instead of using a
function call
• Termination
– Compiler can ignore inline
– Iteration: loop condition fails
– Should be used with small, often-used functions
– Recursion: base case recognized
• Both can have infinite loops • Example:
inline double cube( const double s )
• Balance between performance (iteration) and good { return s * s * s; }
software engineering (recursion)
27 1 // Fig. 11.4: fig11_211.cpp 28
2 // Using default arguments Outline
11.4 Default Arguments 3 #include <iostream>
4
1. Function prototype
5 using std::cout;
• If function parameter omitted, gets default value 6 using std::endl;
2. Print default volume
7
– Can be constants, global variables, or function calls 8 int boxVolume( int length = 1, int width = 1, int height = 1 );
9 2.1 Print volume with
– If not enough parameters specified, rightmost go to their 10 int main() one parameter
defaults 11 {
12 cout << "The default box volume is: " << boxVolume()
2.2 Print with 2
• Set defaults in function prototype 13 << "\n\nThe volume of a box with length 10,\n"
parameters
14 << "width 1 and height 1 is: " << boxVolume( 10 )
int defaultFunction( int x = 1,
15 << "\n\nThe volume of a box with length 10,\n"
int y = 2, int z = 3 ); 16 << "width 5 and height 1 is: " << boxVolume( 10, 5 ) 2.3 Print with all
17 << "\n\nThe volume of a box with length 10,\n" parameters.
18 << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 )
19 << endl; 11. Function definition
20
21 return 0;
22 }
23
24 // Calculate the volume of a box
25 int boxVolume( int length, int width, int height )
26 {
27 return length * width * height;
28 }
29 30
Outline
The default box volume is: 1
11.5 Unary Scope Resolution Operator
The volume of a box with length 10,
width 1 and height 1 is: 10
Program Output
The volume of a box with length 10, • Unary scope resolution operator (::)
width 5 and height 1 is: 50
The volume of a box with length 10,
– Access global variables if a local variable has same name
width 5 and height 2 is: 100
– not needed if names are different
Notice how the rightmost – instead of variable use ::variable
values are defaulted.
5
1 // Fig. 11.5: fig11_24.cpp 31 32
2 // Using the unary scope resolution operator Outline
3
4
#include <iostream>
11.6 Function Overloading
5 using std::cout; 1. Define variables
6 using std::endl;
7
2. Print variables
• Function overloading
8 #include <iomanip>
9 – Having functions with same name and different parameters
10 using std::setprecision;
11 – Should perform similar tasks ( i.e., a function to square
12 const double PI = 11.14159265358979; ints, and function to square floats).
13
14 int main() int square( int x) {return x * x;}
15 {
16 const float PI = static_cast< float >( ::PI );
float square(float x) { return x * x; }
Notice the use of ::
17
18 cout << setprecision( 20 )
– Program chooses function by signature
19 << " Local float value of PI = " << PI • signature determined by function name and parameter types
20 << "\nGlobal double value of PI = " << ::PI << endl;
21 – Can have the same return types
22 return 0;
23 }
Program Output
Local float value of PI = 11.141592741012573242
Global double value of PI = 11.141592653589790007
1 // Fig. 11.6: fig11_25.cpp 33 34
2 // Using overloaded functions Outline
3 #include <iostream>
Functions have same name but
11.7 Function Templates
4
different parameters 1. Define overloaded
5 using std::cout;
6 using std::endl;
function • Function templates
7
8 int square( int x ) { return x * x; } 2. Call function
– Compact way to make overloaded functions
9 – Keyword template
10 double square( double y ) { return y * y; }
11
– Keyword class or typename before every formal type
12 int main() parameter (built in or user defined)
13 { template < class T >
14 cout << "The square of integer 7 is " << square( 7 )
15 << "\nThe square of double 7.5 is " << square( 7.5 )
// or template< typename T >
16 << endl; T square( T value1 )
17
{
18 return 0;
19 } return value1 * value1;
}
– T replaced by type parameter in function call.
The square of integer 7 is 49 Program Output
The square of double 7.5 is 56.25 int x;
int y = square(x);
• If int, all T's become ints
• Can use float, double, long...