You are on page 1of 218

Object-Oriented

Programming Using C++

DATA STRUCTURES
AND ALGORITHMS

Objectives
Looking ahead in this lecture, well
consider:
Abstract Data Types
Encapsulation
Inheritance
Pointers
Polymorphism

Aspects of Object-Oriented
Solution
Principles of object-oriented programming
Encapsulation: Objects combine data and
operations.
Inheritance: Classes inherit properties
from other classes.
Polymorphism: Objects determine
appropriate operations at execution time.

Abstract Data Types


Proper planning is essential to successful
implementation of programs
Typical design methodologies focus on
developing models of solutions before
implementing them
These models emphasize structure and
function of the algorithms used
Initially our attention is on what needs to
be done, not how it is done
So we define program behavior in terms of
operations to be performed on data

Abstract Data Types


(continued)
The details will emerge as we refine the
definitions of the operations
Only then will implementation of those
operations be carried out
As part of this implementation, we must
choose appropriate data structures
A data structure is a technique of storing
and organizing data so it can be used
efficiently
In our program models, data structures are
described by abstract data types (ADTs)

Abstract Data Types


(continued)
ADTs are defined indirectly, in terms of
operations to be performed rather than in
terms of its inner structure
ADTs can then be implemented through
class definitions in an object-oriented
language
For example, consider a stack ADT:

Abstract Data Types


(continued)
A stack is a last-in first-out (LIFO) linear
structure where items can only be added and
removed from one end
Operations on this stack ADT might include:
PUSH add an item to the stack
POP remove the item at the top of the stack
TOP return the value of the item at the top of
the stack
EMPTY determine if the stack is empty
CREATE create a new empty stack
Notice these simply describe the things we can
do, not how they are done
These details will be reserved for implementation

Data Structures and OOP


The notion of a data type is an abstraction that
allows us to hide the details of how the type is
implemented
To use effectively, we concern ourselves with the
operations that can be performed on it that make
it distinctive
While a given programming language may
incorporate some data types, the user may have
to define their own
These new types typically have a distinct
organization that can be exploited to define the
types behavior
The task then is to study the structure of these

Data Structures and OOP


(continued)
This is the opposite of OOP, where we focus on
behavior and try to match the data types to the desired
operations efficiently
We can look at the field of data structures as a tool
building effort that focuses on creating efficient objects
that can be incorporated into programs
From this perspective, classes are defined in terms of
the mechanisms of the class, typically hidden from the
user
By using the features of OOP, the classes can be
designed and modified behind the protections afforded
by principles of encapsulation and data hiding

Data Structures and OOP


(continued)
These protections ensure that the tools
that are created are used only in the way
that is allowed by the public interface of
the class

Encapsulation
Fundamental to object-oriented
programming (OOP) is the notion of an
object
An object is a data structure, combined
with the operations pertinent to that
structure
Most object-oriented languages (OOLs)
define objects through the use of a class
A class is a template which implements
the ADT defining the objects the class
creates

Encapsulation (continued)
The combination of data members and methods in a class is
referred to as data encapsulation
An object, then, can also be defined as the instantiation of a
class, creating an entity that can be used in a program
This concept is a very powerful and useful tool in modern
programming
In non-OOLs, the program code itself is responsible for
determining the associations between data and functions
In contrast, data encapsulation binds the data structure and
its operations together in the class
The program can then focus on the manipulation of these
objects through their associated methods

Encapsulation (continued)
This approach has several advantages:
The strong link between data and operations
better mimics real-world behavior, on which
program models are based
Errors in implementation are confined to the
methods of a particular class in which they
occur, making them easier to detect and
correct
Details of the implementation of the object can
be hidden from other objects to prevent side
effects from occurring
This last point illustrates the principle of
information-hiding

Encapsulation (continued)
These user-accessible components
comprise an objects public interface; the
remaining methods and data are private

Encapsulation (continued)
Information-hiding also means that every
object we use is independent of all other
objects, unless we define methods for
communicating between objects
Even then, the degree to which the objects
interact is precisely defined by the
communication methods, known as
message passing
This is analogous to function calls in
classical programming
An object responds to a message by

Encapsulation (continued)
The class as a creator of objects allows great
freedom to define objects of the same class with
different properties
Default parameters in constructors, combined
with well-crafted methods, allow objects to exhibit
considerable flexibility
Generic classes offer further flexibility by allowing
type parameters to generalize data members and
methods
This allows objects to be modified or replaced by
other objects that are more efficient or better
suited to particular circumstances while the user
interface and message passing remains the same

Inheritance
Inheritance is a technique of reusing existing class
definitions to derive new classes
These new classes (called derived classes or
subclasses or child classes) can inherit the attributes
and behavior of the pre-existing classes (called base
classes or superclasses or parent classes)
This relationship of classes through inheritance forms a
hierarchy, which can be diagrammed
Information hiding can be extended through this
hierarchy by the access the base class allows the
derived class(es)
Derived classes can then add, delete, & modify methods
and data members in their own definitions (known as
overriding)

Inheritance (continued)
The amount of access, and level of
modifications, are controlled by specifying
public, protected, or private in the
derived class header
A derived class with public inheritance
preserves the access classes of the base class
A derived class with protected inheritance
treats public and protected members of the
base class as protected; private members
remain private
Finally, derived classes with private inheritance
treat all members of the base class as private

Inheritance (continued)
Derived classes are also not limited to a single
base class for their inherited attributes
Multiple inheritance is the capability provided
in some OOLs (like C++) that allows a derived
class to inherit from more than one base class
This can create problems if the base classes have
a common ancestor in the inheritance hierarchy
In this situation, the derived class could inherit
multiple copies of the same member, causing
possible errors
This is referred to as the diamond problem, due
to the way the inheritance diagram is formed

Inheritance (continued)

Inheritance (continued)
In this figure the two classes B and C inherit from
A, and D inherits from B and C
The problem occurs if D uses a method defined in
A (and doesnt override it)
If B and C both override it, D could potentially
have two copies with different behaviors, leading
to a compiler error
To avoid this, classes B and C inherit class A as
virtual
This treats A as a direct base class of D, so only
one copy of A is available to inherit, eliminating
the ambiguity

Polymorphism
Polymorphism is the ability, in many OOLs, to
create objects of different types that respond to
method calls having the same name
They differ in that they respond according to
type-specific behavior
Which method is called depends on the time at
which the decision is made about the call
This decision is referred to as binding, and can
occur in different ways
Static binding determines the function call at
compile time
Dynamic binding delays the decision until
run time

Polymorphism (continued)
In C++, dynamic binding can be
implemented by declaring the method
virtual
This allows the method to be selected
based on the value the pointer has instead
of its type
With static binding, a method is chosen
based on the pointers type
This mechanism gives us a very powerful
OOP tool
We can send messages to different objects

Data Abstraction: The


Walls

Object-Oriented Concepts
Object-oriented analysis and design
(OOAD)
Process for solving problems

Solution
Computer program consisting of system of
interacting classes of objects

Object
Has set of characteristics, behaviors related to
solution

Object-Oriented Analysis &


Design
Requirements of a solution
What solution must be, do

Object-oriented design
Describe solution to problem
Express solution in terms of software objects
Create one or more models of solution

Aspects of Object-Oriented
Solution
Principles of object-oriented programming
Encapsulation: Objects combine data and
operations.
Inheritance: Classes inherit properties
from other classes.
Polymorphism: Objects determine
appropriate operations at execution time.

Cohesion
Each module should perform one welldefined task
Benefits

Well named, self-documenting


Easy to reuse
Easier to maintain
More robust

Coupling
Measure of dependence among modules
Dependence
Sharing data structures or calling each others
methods

Modules should be loosely coupled


Highly coupled modules should be avoided

Coupling
Benefits of loose coupling in a system

More adaptable to change


Easier to understand
Increases reusability
Has increased cohesion

Specifications

FIGURE 1-1 The task sort is a module


separate from the MyProgram module

Operation Contracts
Documents
How method can be used
What limitations it has

Specify
Purpose of modules
Data flow among modules
Pre-, post-condition, input, output of each
module

Unusual Conditions
Ways to address invalid conditions:
Assume they will not happen
Ignore such situations
Guess at clients intentions
Return value that signals problem
Throw an exception

Abstraction
Separate purpose of a module from its
implementation
Specifications do not indicate how to
implement
Able to use without knowing implementation

Information Hiding
Abstraction helps identify details that
should be hidden from public view
Ensured no other module can tamper with
these hidden details.

Isolation of the modules cannot be total,


however
Client must know what tasks can be done, how
to initiate a task

Information Hiding

FIGURE 1-2 Tasks communicate through a


slit in the wall

Information Hiding

FIGURE 1-3 A revised implementation


communicates through the same slit in the
wall

Minimal and Complete


Interfaces
Interface for a class made up of publicly
accessible methods and data
Complete interface for a class
Allows programmer to accomplish any
reasonable task

Minimal interface for a class


Contains method if and only if that method is
essential to classs responsibilities

Abstract Data Types (ADT)


Typical operations on data
Add data to a data collection.
Remove data from a data collection.
Ask questions about the data in a data
collection.

An ADT : a collection of data and a set of


operations on data
A data structure : an implementation of an
ADT within a programming language

Abstract Data Types (ADT)

FIGURE 1-4 A dispenser of chilled water,


crushed ice, and ice cubes

Abstract Data Types (ADT)

FIGURE 1-5 A wall of ADT operations isolates


a data
structure from the program that uses it

Designing an ADT
Evolves naturally during the problemsolving process
What data does a problem require?
What operations does a problem require?

ADTs typically have initialization and


destruction operations
Assumed but not specified at this stage

ADTs That Suggest Other


ADTs
You can use an ADT to implement another
ADT
Example: Date-Time objects available in C++
for use in various contexts
Possible to create your own fraction object

to use in some other object which required


fractions

The ADT Bag


Consider the bag to be an abstract data
type.
We are specifying an abstraction inspired by an
actual physical bag
Doesnt do much more than contain its items
Can unordered and possibly duplicate objects
We insist objects be of same or similar types

Knowing just its interface


Can use ADT bag in a program

Identifying Behaviors

FIGURE 1-6 A CRC card for a class Bag

Specifying Data and


Operations

FIGURE 1-7 UML notation for the class Bag

Elements of C++

Introduction
Computer program
Sequence of statements whose objective is to
accomplish a task

Programming
Process of planning and creating a program

Real-world analogy: a recipe for cooking

A Quick Look at a C++


Program

A Quick Look at a C++


Program (contd.)
Sample run:

A Quick Look at a C++


Program (contd.)

A Quick Look at a C++


Program(contd.)

A Quick Look at a C++


Program(contd.)
Variable: a memory location whose
contents can be changed

Figure 2-2 Memory


allocation

Figure 2-3 Memory spaces after the statement length = 6.0;


executes

The Basics of a C++


Program
Function (or subprogram): collection of
statements; when executed, accomplishes
something
May be predefined or standard

Syntax rules: rules that specify which


statements (instructions) are legal or valid
Semantic rules: determine the meaning of
the instructions
Programming language: a set of rules,
symbols, and special words

Comments
Comments are for the reader, not the
compiler
Two types:
Single line: begin with //
// This is a C++ program.
// Welcome to C++ Programming.
Multiple line: enclosed between /* and */
/*
You can include comments that can
occupy several lines.
*/

Special Symbols
Token: the smallest individual unit of a
program written in any language
C++ tokens include special symbols, word
symbols, and identifiers
Special symbols in C++ include:

Reserved Words
(Keywords)
Reserved word symbols (or keywords):
Cannot be redefined within program
Cannot be used for anything other than their
intended use
Examples:

int
float
double
char
const
void
return

Identifiers
Identifier: the name of something that
appears in a program
Consists of letters, digits, and the underscore
character (_)
Must begin with a letter or underscore

C++ is case sensitive


NUMBER is not the same as number

Two predefined identifiers are cout and


cin
Unlike reserved words, predefined
identifiers may be redefined, but it is not a
good idea

Identifiers (contd.)
Legal identifiers in C++:
first
conversion
payRate

Whitespaces
Every C++ program contains whitespaces
Include blanks, tabs, and newline characters

Used to separate special symbols,


reserved words, and identifiers
Proper utilization of whitespaces is
important
Can be used to make the program more
readable

Data Types
Data type: set of values together with a
set of operations
C++ data types fall into three categories:
Simple data type
Structured data type
Pointers

Simple Data Types


Three categories of simple data
Integral: integers (numbers without a decimal)
Can be further categorized:
char, short, int, long, bool, unsigned
char, unsigned short, unsigned int,
unsigned long

Floating-point: decimal numbers


Enumeration type: user-defined data type

Simple Data Types (contd.)

Different compilers may allow different


ranges of values

int Data Type


Examples:
-6728
0
78
+763

Cannot use a comma within an integer


Commas are only used for separating items in
a list

bool Data Type


bool type
Two values: true and false
Manipulate logical (Boolean) expressions

true and false


Logical values

bool, true, and false


Reserved words

char Data Type


The smallest integral data type
Used for single characters: letters, digits,
and special symbols
Each character is enclosed in single quotes
'A', 'a', '0', '*', '+', '$', '&'

A blank space is a character


Written ' ', with a space left between the
single quotes

char Data Type (contd.)


Different character data sets exist
ASCII: American Standard Code for
Information Interchange
Each of 128 values in ASCII code set represents
a different character
Characters have a predefined ordering based
on the ASCII numeric value

Collating sequence: ordering of characters


based on the character set code

Floating-Point Data Types


C++ uses scientific notation to represent
real numbers (floating-point notation)

Floating-Point Data Types


(contd.)
float: represents any real number
Range: -3.4E+38 to 3.4E+38 (four bytes)

double: represents any real number


Range: -1.7E+308 to 1.7E+308 (eight bytes)

Minimum and maximum values of data


types are system dependent

Floating-Point Data Types


(contd.)
Maximum number of significant digits
(decimal places) for float values: 6 or 7
Maximum number of significant digits for
double: 15
Precision: maximum number of significant
digits
Float values are called single precision
Double values are called double precision

Data Types Variables, and


Assignment Statements
To declare a variable, must specify its data
type
Syntax: dataType identifier;
Examples:
int counter;
double interestRate;
char grade;

Assignment statement: variable =


expression
interestRate = 0.05;

Arithmetic Operators,
Operator
Precedence, and
Expressions
C++ arithmetic operators:

+ addition
- subtraction
* multiplication
/ division
% modulus (or remainder) operator

+, -, *, and / can be used with integral and


floating-point data types
Use % only with integral data types

Arithmetic Operators,
Operator Precedence, and
Expressions (contd.)

When you use / with integral data types,


the integral result is truncated (no
rounding)
Arithmetic expressions: contain values and
arithmetic operators
Operands: the number of values on which
the operators will work
Operators can be unary (one operand) or
binary (two operands)

Order of Precedence
All operations inside of () are evaluated
first
*, /, and % are at the same level of
precedence and are evaluated next
+ and have the same level of
precedence and are evaluated last
When operators are on the same level
Performed from left to right (associativity)

3 * 7 - 6 + 2 * 5 / 4 + 6 means
(((3 * 7) 6) + ((2 * 5) / 4 )) + 6

Expressions
Integral expression: all operands are
integers
Yields an integral result
Example: 2 + 3 * 5

Floating-point expression: all operands are


floating-point
Yields a floating-point result
Example: 12.8 * 17.5 - 34.50

Mixed Expressions
Mixed expression:
Has operands of different data types
Contains integers and floating-point

Examples of mixed expressions:


2 + 3.5
6 / 4 + 3.9
5.4 * 2 13.6 + 18

Mixed Expressions (contd.)


Evaluation rules:
If operator has same types of operands
Evaluated according to the type of the
operands
If operator has both types of operands
Integer is changed to floating-point
Operator is evaluated
Result is floating-point
Entire expression is evaluated according to
precedence rules

Type Conversion (Casting)


Implicit type coercion: when value of one
type is automatically changed to another
type
Cast operator: provides explicit type
conversion
static_cast<dataTypeName>(expression)

Type Conversion (contd.)

string Type
Programmer-defined type supplied in
ANSI/ISO Standard C++ library
Sequence of zero or more characters
enclosed in double quotation marks
Null (or empty): a string with no characters
Each character has a relative position in
the string
Position of first character is 0

Length of a string is number of characters


in it
Example: length of "William Jacob" is 13

Variables, Assignment
Statements, and Input
Statements

Data must be loaded into main memory


before it can be manipulated
Storing data in memory is a two-step
process:
Instruct computer to allocate memory
Include statements to put data into memory

Allocating Memory with


Constants and Variables
Named constant: memory location whose
content cant change during execution
Syntax to declare a named constant:
In C++, const is a reserved word

Allocating Memory with


Constants and Variables (contd.)
Variable: memory location whose content
may change during execution
Syntax to declare a named constant:

Putting Data into Variables


Ways to place data into a variable:
Use C++s assignment statement
Use input (read) statements

Assignment Statement
The assignment statement takes the form:
Expression is evaluated and its value is
assigned to the variable on the left side
A variable is said to be initialized the first
time a value is placed into it
In C++, = is called the assignment
operator

Assignment Statement
(contd.)

Saving and Using the Value


of an Expression
To save the value of an expression:
Declare a variable of the appropriate data type
Assign the value of the expression to the
variable that was declared
Use the assignment statement

Wherever the value of the expression is


needed, use the variable holding the value

Declaring & Initializing


Variables
Not all types of variables are initialized
automatically
Variables can be initialized when declared:
int first=13, second=10;
char ch=' ';
double x=12.6;

All variables must be initialized before


they are used
But not necessarily during declaration

Input (Read) Statement


cin is used with >> to gather input
This is called an input (read) statement
The stream extraction operator is >>
For example, if miles is a double variable
cin >> miles;
Causes computer to get a value of type double
and places it in the variable miles

Input (Read) Statement


(contd.)
Using more than one variable in cin allows
more than one value to be read at a time
Example: if feet and inches are variables
of type int, this statement:
cin >> feet >> inches;
Inputs two integers from the keyboard
Places them in variables feet and inches
respectively

Input (Read) Statement


(contd.)

Increment and Decrement


Operators
Increment operator: increase variable
by 1
Pre-increment: ++variable
Post-increment: variable++

Decrement operator: decrease variable


by 1

Pre-decrement: --variable
Post-decrement: variable
x = difference
5;
x between
= 5;
What is the
y = ++x;
y = x++;

following?

the

Output
The syntax of cout and << is:
Called an output statement

The stream insertion operator is <<


Expression evaluated and its value is
printed at the current cursor position on
the screen

Output (contd.)
A manipulator is used to format the output
Example: endl causes insertion point to move
to beginning of next line

Output (contd.)
The new line character is '\n'
May appear anywhere in the string
cout << "Hello there.";
cout << "My name is James.";

Output:
Hello there.My name is James.
cout << "Hello there.\n";
cout << "My name is James.";

Output :
Hello there.
My name is James.

Output (contd.)

Preprocessor Directives
C++ has a small number of operations
Many functions and symbols needed to run
a C++ program are provided as collection
of libraries
Every library has a name and is referred to
by a header file
Preprocessor directives are commands
supplied to the preprocessor program
All preprocessor commands begin with #
No semicolon at the end of these
commands

Preprocessor Directives
(contd.)
Syntax to include a header file:
For example:
#include <iostream>
Causes the preprocessor to include the header
file iostream in the program

Preprocessor commands are processed


before the program goes through the
compiler

namespace and Using cin and


cout in a Program
cin and cout are declared in the header
file iostream, but within std namespace
To use cin and cout in a program, use the
following two statements:
#include <iostream>
using namespace std;

Using the string Data Type in a


Program
To use the string type, you need to
access its definition from the header file
string
Include the following preprocessor
directive:
#include <string>

Creating a C++ Program


A C++ program is a collection of functions,
one of which is the function main
The first line of the function main is called
the heading of the function:
int main()

The statements enclosed between the


curly braces ({ and }) form the body of the
function

Creating a C++ Program


(contd.)
A C++ program contains two types of
statements:
Declaration statements: declare things, such as
variables
Executable statements: perform calculations,
manipulate data, create output, accept input,
etc.

Creating a C++ Program


(contd.)
C++ program has two parts:
Preprocessor directives
The program

Preprocessor directives and program


statements constitute C++ source code
(.cpp)
Compiler generates object code (.obj)
Executable code is produced and saved in
a file with the file extension .exe

Debugging: Understanding and


Fixing Syntax Errors
Compile a program
Compiler will identify the syntax errors
Specifies the line numbers where the errors
occur
Example2_Syntax_Errors.cpp
c:\chapter 2 source code\example2_syntax_errors.cpp(9) : error
C2146: syntax error :
missing ';' before identifier 'num'
c:\chapter 2 source code\example2_syntax_errors.cpp(11) :
error C2065: 'tempNum' :
undeclared identifier

Program Style and Form:


Syntax
Syntax rules: indicate what is legal and
what is not legal
Errors in syntax are found in compilation
int x;
//Line 1
int y
//Line 2: error
double z;//Line 3
y = w + x; //Line 4: error

Use of Blanks
In C++, you use one or more blanks to
separate numbers when data is input
Blanks are also used to separate reserved
words and identifiers from each other and
from other symbols
Blanks must never appear within a
reserved word or identifier

Use of Semicolons,
Brackets, and Commas
All C++ statements end with a semicolon
Also called a statement terminator

{ and } are not C++ statements


Can be regarded as delimiters

Commas separate items in a list

Semantics
Semantics: set of rules that gives meaning
to a language
Possible to remove all syntax errors in a
program and still not have it run
Even if it runs, it may still not do what you
meant it to do

Ex: 2 + 3 * 5 and (2 + 3) * 5
are both syntactically correct expressions,
but have different meanings

Naming Identifiers
Identifiers can be self-documenting:
CENTIMETERS_PER_INCH

Avoid run-together words :


annualsale
Solution:
Capitalizing the beginning of each new
word: annualSale
Inserting an underscore just before a new
word: annual_sale

Prompt Lines
Prompt lines: executable statements that
inform the user what to do
cout << "Please enter a number between 1 and 10 and "
<< "press the return key" << endl;
cin >> num;

Always include prompt lines when input is


needed from users

Documentation
A well-documented program is easier to
understand and modify
You use comments to document programs
Comments should appear in a program to:
Explain the purpose of the program
Identify who wrote it
Explain the purpose of particular statements

Form and Style


Consider two ways of declaring variables:
Method 1
int feet, inch;
double x, y;
Method 2
int feet,inch;double x,y;

Both are correct; however, the second is


hard to read

More on Assignment
Statements
Two forms of assignment
Simple and compound
Compound operators provide more concise
notation

Compound operators: +=, -=, *=, /=, %=


Simple assignment
x = x * y;

Compound assignment
x *= y;

Pointers
A variable defined in a program has two
important attributes
Its content or value (what it stores)
Its location or address (where it is)

Normally, we access a variables contents


by specifying the variables name in an
operation
However, it is possible to store a variables
address in another variable
This new variable is called a pointer; it
allows us access to the original variables

Pointers (continued)
Pointers are defined much the same as other variables
They have a type; in this case the type of variable they point
to
They have a user-defined name
The name is preceded by an asterisk (*) to indicate the
variable is a pointer

Given the declarations


int i=15,j,*p,*q;
i and j are integer variables, while p and q are pointers
to integer variables
If the variable i is at memory location 1080, and each
variable occupies two bytes, figure 1-1a illustrates this
layout

Pointers (continued)

Fig. 1-1 Changes of values after assignments are made using pointer variables; note that (b) and (c)
show the same situation, and so do (d) and (e), (g) and (h), (i) and (j), (k) and (l), and (m) and (n)

Pointers (continued)
To assign a variables address to a pointer, the
address-of operator (&) is placed before the variable
For pointer p to point to variable i, we write
p = &i;
This pointer is then said to point to that variable
This is shown in figure 1-1(b); a common way to draw
this relationship is shown in figure 1-1(c)
To access the value a pointer points to, we have to
dereference the pointer, using the dereference
operator, an asterisk (*)
So *p refers to the location stored in p, the address of i

Pointers (continued)
This is shown in figure 1.1(d); figures (e) to
(n) show other examples

Pointers (continued)
In addition to variables, pointers can be used to
access dynamically created locations
These are created during runtime using the memory
manager
Two functions are used to handle dynamic memory
To allocate memory, new is used; it returns the address of
the allocated memory, which can be assigned to a pointer
p = new int;
To release the memory pointed at, delete is used
delete p;

Care must be exercised when using this type of


memory operation

Pointers (continued)
One problem can arise when an object is deleted
without modifying the value of the pointer
The pointer still points to the memory location of
the deallocated memory
This creates the dangling reference problem
Attempting to dereference the pointer will cause
an error
To avoid this, after deleting the object, the pointer
should be set to a known address or NULL, which
is equivalent to 0
p = NULL; or p = 0;

Pointers (continued)
The second type of problem that can occur with dynamic
memory usage is the memory leak
This occurs when the same pointer is used in consecutive
allocations, such as:
p = new int;
p = new int;
Since the second allocation occurs without deleting the
first, the memory from the first allocation becomes
inaccessible
Depending on code structure, this leak can accumulate
until no memory is available for further allocation
To avoid this, memory needs to be deallocated when no
longer in use

Pointers (continued)
Pointers and Arrays
Pointers ability to access memory locations
through their addresses provides us with
numerous processing advantages
Typically, arrays in C++ are declared before
they can be used, known as static
declaration
This means the size of the array must be
determined before it is used
This is wasteful if the array is too large, or a
limitation if the array is too small
However, the name of an array is nothing more
than a label for the beginning of the array in

Pointers (continued)
Pointers and Arrays (continued)
For example, an array declared:
int temp[7];
would appear in memory as:

In array notation, we access the elements by subscripting:


temp[0], temp[1], etc.
But we can also dereference the pointer to achieve the
same results: *temp is equivalent to temp[0]
And we can access additional elements through pointer
arithmetic

Pointers (continued)
Pointers and Arrays (continued)
In pointer arithmetic, we can add an offset to the base address
of the array: temp + 1, temp + 2, etc. and dereference the
result
So *(temp + 1) is the same as temp[1], *(temp + 2) is
equivalent to temp[2], etc.
And as long as we dont try to change the value of temp, we
can use this alternate approach to access the arrays elements
Now remember that a pointer can be used in the allocation of
memory without a name, through the use of new
This means that we can also declare an array dynamically,
via
int *p; p = new int[n];
As long as the value of n is known when the declaration is
executed, the array can be of arbitrary size

Pointers (continued)
Pointers and Arrays (continued)
Now, a reference to an element of the array is
constructed by adding the elements location to p
and dereferencing, as before
And we can assign other pointers to the array by
simply declaring them and copying the value of p
into the new pointer, if needed
This also allows us to conveniently dispose of an
array when we no longer need it, using:
delete[] p;
The brackets indicate that an array is to be deleted;
p is the pointer to that array

Pointers (continued)
Pointers and Copy Constructors
A potential problem can arise when copying
data from one object to another if one of the
data members is a pointer
The default behavior is to copy the items
member by member
Because the value of a pointer is an address,
this address is copied to the new object
Consequently the new objects pointer points
to the same data as the old objects pointer,
instead of being distinct
To correct this, the user must create a copy
constructor which will copy not only the

Pointers (continued)
Pointers and Copy Constructors (continued)

Fig. 1-2 Illustrating the necessity of using a copy constructor for objects with pointer members

Pointers (continued)
Pointers and Destructors
When a local object goes out of scope, the
memory associated with it is released
Unfortunately, if one of the object members is
a pointer, the pointers memory is released,
leaving the object pointed at inaccessible
To avoid this memory leak, objects that contain
pointers need to have destructors written for
them
A destructor is a code construct that is
automatically called when its associated object
is deleted
It can specify special processing to occur, such

Pointers (continued)
Pointers and Reference Variables
There is a close correspondence between pointers
and reference variables
This is because reference variables are implemented
as constant pointers
Given the declarations:
int n = 5,*p = &n,&r = n;
a change to the value of n via any of the three will be
reflected in the other two
Thus n = 7 or *p = 7, or r = 7 accomplishes the
same result; the value of n is now 7
So we can dereference a pointer, or use a reference
directly to access the original objects value

Pointers (continued)
Pointers and Reference Variables (continued)
We do have to exercise care in declaring pointers, though,
because
int *const
declares a constant pointer to an integer, while
const int *
declares a pointer to a constant integer
The latter can cause errors if we attempt to assign a value
through a dereferenced pointer
Reference variables are valuable in working with functions, as
they allow us to modify the values of arguments
They can also be returned from a function
While pointers can be used instead, they have to be
dereferenced

Pointers (continued)
Pointers and Reference Variables
(continued)
We do have to be careful when we use
references in classes
It is possible to compromise information hiding
if a public method returns a reference to a
private data member
This reference, as an address, allows bypassing
of the protection mechanisms provided in the
class definition
Data corruption can result

Pointers (continued)
Pointers and Functions
The same characteristics of variables value
(or contents) and location (or address) can
also be applied to functions
A functions value is the result it returns, and
its address is the memory location of the
functions body
So we can use a pointer to a function to access
it
Given a function temp, its name, temp, is a
pointer to the function and *temp is the
function itself
Following the dereferenced pointer with an

Input/Output

I/O Streams and Standard


I/O Devices
I/O: sequence of bytes (stream of bytes)
from source to destination
Bytes are usually characters, unless program
requires other types of information
Stream: sequence of characters from source to
destination
Input stream: sequence of characters from an
input device to the computer
Output stream: sequence of characters from
the computer to an output device

I/O Streams and Standard


I/O Devices (contd.)
Use iostream header file to receive data
from keyboard and send output to the
screen
Contains definitions of two data types:
istream: input stream
ostream: output stream
Has two variables:
cin: stands for common input
cout: stands for common output

I/O Streams and Standard


I/O Devices (contd.)
Variable declaration is similar to:
istream cin;
ostream cout;

To use cin and cout, the preprocessor


directive #include <iostream> must be
used
Input stream variables: type istream
Output stream variables: type ostream

cin and the Extraction


Operator >>
The syntax of an input statement using
cin and the extraction operator >> is:
The extraction operator >> is binary
Left-side operand is an input stream variable
Example: cin
Right-side operand is a variable

cin and the Extraction


Operator >> (contd.)
No difference between a single cin with
multiple variables and multiple cin
statements with one variable
When scanning, >> skips all whitespace
Blanks and certain nonprintable characters

>> distinguishes between character 2 and


number 2 by the right-side operand of >>
If type char or int (or double), the 2 is treated
as a character or as a number 2

cin and the Extraction


Operator >> (contd.)

Entering a char value into an int or


double variable causes serious errors,
called input failure

cin and the Extraction


Operator >> (contd.)
When reading data into a char variable
>> skips leading whitespace, finds and stores
only the next character
Reading stops after a single character

To read data into an int or double


variable
>> skips leading whitespace, reads + or - sign
(if any), reads the digits (including decimal)
Reading stops on whitespace non-digit
character

cin and the Extraction


Operator >> (contd.)

cin and the Extraction


Operator >> (contd.)

cin and the Extraction


Operator >> (contd.)

Using Predefined Functions


in a Program
Function (subprogram): set of instructions
When activated, it accomplishes a task

main executes when a program is run


Other functions execute only when called
C++ includes a wealth of functions
Predefined functions are organized as a
collection of libraries called header files

Using Predefined Functions


in a Program (contd.)
Header file may contain several functions
To use a predefined function, you need the
name of the appropriate header file
You also need to know:
Function name
Number of parameters required
Type of each parameter
What the function is going to do

Using Predefined Functions


in a Program (contd.)
To use pow (power), include cmath
Two numeric parameters
Syntax: pow(x,y) = xy
x and y are the arguments or parameters
In pow(2,3), the parameters are 2 and 3

cin and the get Function


The get function
Inputs next character (including whitespace)
Stores in memory location indicated by its
argument

The syntax of cin and the get function:


varChar
Is a char variable
Is the argument (or parameter) of the function

cin and the ignore Function


ignore function
Discards a portion of the input

The syntax to use the function ignore is:


intExp is an integer expression
chExp is a char expression

If intExp is a value m, the statement says to


ignore the next m characters or all characters
until the character specified by chExp

cin and the ignore Function


(contd.)

putback and peek Functions


putback function
Places previous character extracted by the get
function from an input stream back to that
stream

peek function
Returns next character from the input stream
Does not remove the character from that
stream

putback and peek Functions


(contd.)
The syntax for putback:
istreamVar: an input stream variable (cin)
ch is a char variable

The syntax for peek:


istreamVar: an input stream variable (cin)
ch is a char variable

The Dot Notation Between


I/O Stream Variables and
I/O Functions
A precaution

In the statement
cin.get(ch);

cin and get are two separate identifiers


separated by a dot
Dot separates the input stream variable name
from the member, or function, name
In C++, dot is the member access operator

Input Failure
Things can go wrong during execution
If input data does not match
corresponding variables, program may run
into problems
Trying to read a letter into an int or
double variable will result in an input
failure
If an error occurs when reading data
Input stream enters the fail state

The clear Function


Once in a fail state, all further I/O
statements using that stream are ignored
The program continues to execute with
whatever values are stored in variables
This causes incorrect results

The clear function restores input stream


to a working state

Output and Formatting


Output
Syntax of cout when used with <<
expression is evaluated
value is printed
manipulator is used to format the output
Example: endl

setprecision Manipulator
Syntax:
Outputs decimal numbers with up to n
decimal places
Must include the header file iomanip:
#include <iomanip>

fixed Manipulator
fixed outputs floating-point numbers in a
fixed decimal format
Example: cout << fixed;
Disable by using the stream member function
unsetf
Example: cout.unsetf(ios::fixed);

scientific manipulator: outputs floatingpoint numbers in scientific format

showpoint Manipulator
showpoint forces output to show the
decimal point and trailing zeros
Examples:
cout << showpoint;
cout << fixed << showpoint;

setw
Outputs the value of an expression in a
specified number of columns
cout << setw(5) << x << endl;

If number of columns exceeds the number


of columns required by the expression
Output of the expression is right-justified
Unused columns to the left are filled with
spaces

Must include the header file iomanip

Additional Output
Formatting Tools
Additional formatting tools that give you
more control over your output:
setfill manipulator
left and right manipulators
unsetf manipulator

setfill Manipulator
Output stream variables can use setfill
to fill unused columns with a character
Example:
cout << setfill('#');

left and right


Manipulators
left: left-justifies the output
Disable left by using unsetf
right: right-justifies the output

Types of Manipulators
Two types of manipulators:
With parameters
Without parameters

Parameterized: require iomanip header


setprecision, setw, and setfill

Nonparameterized: require iostream


header
endl, fixed, showpoint, left, and flush

Input/Output and the


string Type
An input stream variable (cin) and >>
operator can read a string into a variable
of the data type string
Extraction operator
Skips any leading whitespace characters
Reading stops at a whitespace character

The function getline


Reads until end of the current line

Debugging: Understanding
Logic Errors and Debugging
with cout statements
Syntax errors
Reported by the compiler

Logic errors

Typically not caught by the compiler


Spot and correct using cout statements
Temporarily insert an output statement
Correct problem
Remove output statement

File Input/Output
File: area in secondary storage to hold info
File I/O is a five-step process
1. Include fstream header
2. Declare file stream variables
3. Associate the file stream variables with the
input/output sources
4. Use the file stream variables with >>, <<, or
other input/output functions
5. Close the files

Control Structures I
(Selection)

Control Structures
A computer can proceed:

In sequence
Selectively (branch): making a choice
Repetitively (iteratively): looping
By calling a function

Two most common control structures:


Selection
Repetition

Control Structures (contd.)

Selection: if and if...else


Execution of selection or repetition
requires execution of a logical expression:
Evaluates to true or false
8 is greater than 3

Relational Operators
(contd.)

Relational Operators and


Simple Data Types
Conditional statements: only executed if
certain conditions are met
Condition: represented by a logical
(Boolean) expression that evaluates to a
logical (Boolean) value of true or false
Relational operators:
Allow comparisons
Require two operands (binary)
Evaluate to true or false

Relational Operators and


Simple Data Types (contd.)
Relational operators can be used with all
three simple data types:
8 < 15 evaluates to true
6 != 6 evaluates to false
2.5 > 5.8 evaluates to false
5.9 <= 7.5 evaluates to true

Comparing Characters
Expression of char values with relational
operators
Result depends on machines collating
sequence
ASCII character set

Logical (Boolean) expressions


Expressions such as 4 < 6 and 'R' > 'T
Returns an integer value of 1 if the logical
expression evaluates to true
Returns an integer value of 0 otherwise

One-Way Selection
One-way selection syntax:

Statement is executed if the value of the


expression is true
Statement is bypassed if the value is
false; program goes to the next
statement
Expression is called a decision maker

One-Way Selection (contd.)

Two-Way Selection
Two-way selection syntax:

If expression is true, statement1 is


executed; otherwise, statement2 is
executed
statement1 and statement2 are any C++
statements

Two-Way Selection (contd.)

The int Data Type and


Logical (Boolean)
Expressions

Earlier versions of C++ did not provide


built-in data types that had Boolean values
Logical expressions evaluate to either 1 or
0
Logical expression value was stored in a
variable of the data type int

Can use the int data type to manipulate


logical (Boolean) expressions

bool Data Type and Logical


(Boolean) Expressions
The data type bool has logical (Boolean)
values true and false
bool, true, and false are reserved words
The identifier true has the value 1
The identifier false has the value 0

Logical (Boolean) Operators


and Logical Expressions
Logical (Boolean) operators: enable you to
combine logical expressions

Logical (Boolean) Operators


and Logical Expressions
(contd.)

Logical (Boolean) Operators


and Logical Expressions
(contd.)

Logical (Boolean) Operators


and Logical Expressions
(contd.)

Order of Precedence
Relational and logical operators are
evaluated from left to right
The associativity is left to right

Parentheses can override precedence

Order of Precedence
(contd.)

Order of Precedence
(contd.)

Order of Precedence
(contd.)

Order of Precedence
(contd.)

Relational Operators and


the
string Type
Relational operators can be applied to
strings

Strings are compared character by character,


starting with the first character
Comparison continues until either a mismatch
is found or all characters are found equal
If two strings of different lengths are compared
and the comparison is equal to the last
character of the shorter string
The shorter string is less than the larger
string

Relational Operators and


the
string Type (contd.)
Suppose we have the following
declarations:
string
string
string
string
string

str1
str2
str3
str4
str4

=
=
=
=
=

"Hello";
"Hi";
"Air";
"Bill";
"Big";

Relational Operators and


the
string Type (contd.)

Relational Operators and


the
string Type (contd.)

Relational Operators and


the
string Type (contd.)

Compound (Block of)


Statements
Compound statement (block of
statements):

A compound statement functions like a


single statement

Compound (Block of)


Statements (contd.)
if (age >
{
cout <<
cout <<
}
else
{
cout <<
cout <<
}

18)
"Eligible to vote." << endl;
"No longer a minor." << endl;

"Not eligible to vote." << endl;


"Still a minor." << endl;

Multiple Selections: Nested


if
Nesting: one control statement is located
within another
An else is associated with the most recent
if that has not been paired with an else

Multiple Selections: Nested


if (contd.)

Comparing ifelse
Statements with a Series of
if Statements

Comparing ifelse
Statements with if
Statements (contd.)

Short-Circuit Evaluation
Short-circuit evaluation: evaluation of a
logical expression stops as soon as the
value of the expression is known
Example:
(age >= 21) || ( x == 5) //Line 1
(grade == 'A') && (x >= 7) //Line 2

Comparing Floating-Point
Numbers for Equality: A
Precaution

Comparison of floating-point numbers for


equality may not behave as you would
expect
Example:
1.0 == 3.0/7.0 + 2.0/7.0 + 2.0/7.0
evaluates to false
Why? 3.0/7.0 + 2.0/7.0 + 2.0/7.0 =
0.99999999999999989

Solution: use a tolerance value


Example: if fabs(x y) < 0.000001

Associativity of Relational
Operators: A Precaution

Associativity of Relational
Operators: A Precaution
(contd.)
num = 5

num = 20

Avoiding Bugs by Avoiding


Partially Understood
Concepts and Techniques
Must use concepts and techniques
correctly

Otherwise solution will be either incorrect or


deficient

If you do not understand a concept or


technique completely
Dont use it
Save yourself an enormous amount of
debugging time

Input Failure and the if


Statement
If input stream enters a fail state
All subsequent input statements associated
with that stream are ignored
Program continues to execute
May produce erroneous results

Can use if statements to check status of


input stream
If stream enters the fail state, include
instructions that stop program execution

Confusion Between the


Equality (==) and
Assignment (=) Operators

C++ allows you to use any expression that


can be evaluated to either true or false
as an expression in the if statement:
if (x = 5)
cout << "The value is five." << endl;

The appearance of = in place of ==


resembles a silent killer
It is not a syntax error
It is a logical error

Conditional Operator (?:)


Conditional operator (?:)
Ternary operator: takes 3 arguments

Syntax for the conditional operator:


expression1 ? expression2 : expression3

If expression1 is true, the result of the


conditional expression is expression2
Otherwise, the result is expression3

Example: max = (a >= b) ? a : b;

Program Style and Form


(Revisited): Indentation
A properly indented program:
Helps you spot and fix errors quickly
Shows the natural grouping of statements

Insert a blank line between statements


that are naturally separate
Two commonly used styles for placing
braces
On a line by themselves
Or left brace is placed after the expression, and
the right brace is on a line by itself

Using Pseudocode to
Develop, Test, and Debug a
Program
Pseudocode, or just pseudo

Informal mixture of C++ and ordinary


language
Helps you quickly develop the correct structure
of the program and avoid making common
errors

Use a wide range of values in a walkthrough to evaluate the program

switch Structures
switch structure: alternate
to if-else
switch (integral) expression
is evaluated first
Value of the expression determines
which corresponding action is taken
Expression is sometimes
called the selector

switch Structures
(contd.)

switch Structures (contd.)


One or more statements may follow a
case label
Braces are not needed to turn multiple
statements into a single compound
statement
When a case value is matched, all
statements after it execute until a
break is encountered
The break statement may or may not
appear after each statement
switch, case, break, and default are
reserved words

switch Structures (contd.)

Avoiding Bugs: Revisited


To output results correctly
Consider whether the switch structure must
include a break statement after each cout
statement

Terminating a Program with


the assert Function
Certain types of errors are very difficult to
catch
Example: division by zero

assert function: useful in stopping


program execution when certain elusive
errors occur

The assert Function


(contd.)
Syntax:

expression is any logical expression

If expression evaluates to true, the next


statement executes
If expression evaluates to false, the
program terminates and indicates where in
the program the error occurred
To use assert, include cassert header file

The assert Function


(contd.)
assert is useful for enforcing
programming constraints during program
development
After developing and testing a program,
remove or disable assert statements
The preprocessor directive #define
NDEBUG must be placed before the
directive #include <cassert> to disable
the assert statement

You might also like