SlideShare a Scribd company logo
1 of 568
Download to read offline
www.cyberlabzone.com
C++ Programming
Topics for C++ Language
1.Introduction to C++ language
2.Structured/OO Programming
3.Memory Concepts
4.Arithmetic
5.Control Structure
6.Functions
7.Arrays
8.Pointers
9.Structures
10.Inheritance
11.Polymorphism
12.Multiple Inheritance
13.Templetes
14.Stacks/Queue
15.Exception Handling
16.Preprocessing
17.Unified Modeling Language
Introduction to C++ language
Course Description
 An introduction to the development of programs using C++.
 Emphasis is given to the development of program modules that can function
independently.
 Object-oriented design
 The theory of data structures and programming language design is continued.
Course Information
Computer Languages
 Machine language
 Generally consist of strings of numbers - Ultimately 0s and 1s -
Machine-dependent
 Example: +1300042774
+1400593419
 Assembly language
 English-like abbreviations for elementary operations
 Incomprehensible to computers - Convert to machine language
 Example: LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY
 High-level languages
 Similar to everyday English, use common mathematical notations
 Compiler/Interpreter
 Example:
grossPay = basePay + overTimePay
History of C and C++
 History of C
 Evolved from two other programming languages
 BCPL and B: “Typeless” languages
 Dennis Ritchie (Bell Lab): Added typing, other features
 1989: ANSI standard/ ANSI/ISO 9899: 1990
 History of C++
 Early 1980s: Bjarne Stroustrup (Bell Lab)
 Provides capabilities for object-oriented programming
 Objects: reusable software components
 Object-oriented programs
 Building block approach” to creating programs
 C++ programs are built from pieces called classes and functions
 C++ standard library: Rich collections of existing classes and functions
Structured/OO Programming
 Structured programming (1960s)
 Disciplined approach to writing programs
 Clear, easy to test and debug, and easy to modify
 E.g.Pascal:1971: Niklaus Wirth
 OOP
 “Software reuse”
 “Modularity”
 “Extensible”
 More understandable, better organized and easier to maintain than procedural
programming
Basics of a Typical C++
Environment
 C++ systems
 Program-development environment
 Language
 C++ Standard Library
 C++ program names extensions
 .cpp
 .cxx
 .cc
 .C
Basics of a Typical C++
Environment
Phases of C++ Programs:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
Loader
Primary
Memory
Program is created in
the editor and stored
on disk.
Preprocessor program
processes the code.
Loader puts program
in memory.
CPU takes each
instruction and
executes it, possibly
storing new data
values as the program
executes.
Compiler
Compiler creates
object code and stores
it on disk.
Linker links the object
code with the libraries,
creates an executable
file and stores it on disk
Editor
Preprocessor
Linker
CPU
Primary
Memory
.
.
.
.
.
.
.
.
.
.
.
.
Disk
Disk
Disk
Disk
Disk
Basics of a Typical C++
Environment
 Common Input/output functions
 cin
 Standard input stream
 Normally keyboard
 cout
 Standard output stream
 Normally computer screen
 cerr
 Standard error stream
 Display error messages
 Comments: C’s comment /* .. */ OR Begin with // or
 Preprocessor directives: Begin with #
 Processed before compiling
A Simple Program: Printing a
Line of Text
 Standard output stream object
 std::cout
 “Connected” to screen
 <<
 Stream insertion operator
 Value to right (right operand) inserted into output stream
 Namespace
 std:: specifies that entity belongs to “namespace” std
 std:: removed through use of using statements
 Escape characters: 
 Indicates “special” character output
1 // Example 1
2 // A first program in C++.
3 #include <iostream>
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout << "Welcome to C++!n";
9
10 return 0; // indicate that program ended successfully
11
12 } // end function main
Welcome to C++!
A Simple Program: Printing a
Line of Text
Escape Sequence Description
n Newline. Position the screen cursor to the
beginning of the next line.
t Horizontal tab. Move the screen cursor to the next
tab stop.
r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
a Alert. Sound the system bell.
 Backslash. Used to print a backslash character.
" Double quote. Used to print a double quote
character.
Memory Concepts
 Variable names
 Correspond to actual locations in computer's memory
 Every variable has name, type, size and value
 When new value placed into variable, overwrites previous value
 std::cin >> integer1;
 Assume user entered 45
 std::cin >> integer2;
 Assume user entered 72
 sum = integer1 + integer2;
integer1 45
integer1 45
integer2 72
integer1 45
integer2 72
sum 117
Arithmetic
 Arithmetic calculations
 * : Multiplication
 / : Division
 Integer division truncates remainder
7 / 5 evaluates to 1
 % : Modulus operator returns remainder
7 % 5 evaluates to 2
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division
Modulus
Evaluated second. If there are several, they re
evaluated left to right.
+ or - Addition
Subtraction
Evaluated last. If there are several, they are
evaluated left to right.
Decision Making: Equality and
Relational Operators
 if structure
 Make decision based on truth or falsity of condition
 If condition met, body executed
 Else, body not executed
 Equality and relational operators
 Equality operators
 Same level of precedence
 Relational operators
 Same level of precedence
 Associate left to right
Decision Making: Equality and
Relational Operators
Standard algebraic
equality operator or
relational operator
C++ equality
or relational
operator
Example
of C++
condition
Meaning of
C++ condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
 >= x >= y x is greater than or equal to y
 <= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
 != x != y x is not equal to y
Algorithms /pseudocode
 Computing problems
 Solved by executing a series of actions in a specific order
 Algorithm: a procedure determining
 Actions to be executed
 Order to be executed
 Example: recipe
 Program control
 Specifies the order in which statements are executed
 Pseudocode
 Artificial, informal language used to develop algorithms
 Similar to everyday English
Control Structures
 Sequential execution
 Statements executed in order
 Transfer of control
 Next statement executed not next one in sequence
 Structured programming – “goto”-less programming
 3 control structures to build any program
 Sequence structure
 Programs executed sequentially by default
 Selection structures
 if, if/else, switch
 Repetition structures
 while, do/while, for
Keywords
 C++ keywords
 Cannot be used as identifiers or variable names
C++ Keywords
Keywords common to the
C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
Control Structures
 Flowchart
 Graphical representation of an algorithm
 Special-purpose symbols connected by arrows (flowlines)
 Rectangle symbol (action symbol)
 Any type of action
 Oval symbol
 Beginning or end of a program, or a section of code (circles)
Exercise: Find greater of three numbers
if/else Selection Structure
 Ternary conditional operator (?:)
 Three arguments (condition, value if true, value if false)
 Code could be written:
cout << ( grade >= 60 ? “Passed” : “Failed” );
truefalse
print “Failed” print “Passed”
grade >= 60
Condition Value if true Value if false
while Repetition Structure
 Repetition structure
 Counter-controlled
 While/do while loop: repeated until condition becomes false
 For: loop repeated until counter reaches certain value Flowchart
representation?
 Sentinel value
 Indicates “end of data entry”
 Sentinel chosen so it cannot be confused with regular input
 Example
int product = 2;
while ( product <= 1000 ) {
product = 2 * product;
cout << product;
}
Flowchart representation?
What is the output?
switch Multiple-Selection
Structure
 switch
 Test variable for multiple values
 Series of case labels and optional default case
switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch
case value2:
case value3: // taken if variable == value2 or == value3
statements
break;
default: // taken if none matches
statements
break;
}
break and continue Statements
 break statement
 Immediate exit from while, for, do/while, switch
 Program continues with first statement after structure
 Common uses
 Escape early from a loop
 Skip the remainder of switch
Logical Operators
 Used as conditions in loops, if statements
 && (logical AND)
 true if both conditions are true
if ( gender == 1 && age >= 65 )
++seniorFemales;
 || (logical OR)
 true if either of condition is true
if ( semesterAverage >= 90 || finalExam >= 90 )
cout << "Student grade is A" << endl;
Logical Operators
 ! (logical NOT, logical negation)
 Returns true when its condition is false, & vice versa
if ( !( grade == sentinelValue ) )
cout << "The next grade is " << grade << endl;
Alternative:
if ( grade != sentinelValue )
cout << "The next grade is " << grade << endl;
Confusing Equality (==) and Assignment (=)
Operators
 Common error
 Does not typically cause syntax errors
 Aspects of problem
 Expressions that have a value can be used for decision
 Zero = false, nonzero = true
 Assignment statements produce a value (the value to be assigned)
if == was replaced with =
if ( payCode = 4 )
cout << "You get a bonus!" << endl;
What happens?
Confusing Equality (==) and Assignment (=)
Operators
 Lvalues
 Expressions that can appear on left side of equation
 Can be changed
x = 4;
 Rvalues
 Only appear on right side of equation
 Constants, such as numbers (i.e. cannot write 4 = x;)
 Lvalues can be used as rvalues, but not vice versa
Structured-Programming Summary
 Structured programming
 Programs easier to understand, test, debug and modify
 Rules for structured programming
 Only use single-entry/single-exit control structures
 Rules
1) Begin with the “simplest flowchart”
2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence
3) Any rectangle (action) can be replaced by any control structure (sequence, if,
if/else, switch, while, do/while or for)
4) Rules 2 and 3 can be applied in any order and multiple times
Structured-Programming Summary
Representation of Rule 3 (replacing any rectangle with a control structure)
Rule 3
Rule 3Rule 3
Program Components in C++
 Modules: functions and classes
 Programs use new and “prepackaged” modules
 New: programmer-defined functions, classes
 Prepackaged: from the standard library
 Functions invoked by function call
 Function name and information (arguments) it needs
 Function definitions
 Only written once
 Hidden from other functions
Functions
 Functions
 Modularize a program
 Software reusability
 Call function multiple times
 Local variables
 Known only in the function in which they are defined
 All variables declared in function definitions are local variables
 Parameters
 Local variables passed to function when called
 Provide outside information
Math Library Functions
Perform common mathematical calculations
Include the header file <cmath>
Functions called by writing
functionName (argument); or
functionName (argument1, argument2, …);
Example
cout << sqrt( 900.0 );
All functions in math library return a double
Function arguments can be
Constants: sqrt( 4 );
Variables: sqrt( x );
Expressions:
 sqrt( sqrt( x ) ) ;
 sqrt( 3 - 6x );
Other functions
 ceil(x), floor(x), log10(x), etc.
Function Definitions
Function prototype
int square( int );
Calling/invoking a function
square(x);
Format for function definition
return-value-type function-name( parameter-list )
{
declarations and statements
}
Prototype must match function definition
Function prototype
double maximum( double, double, double );
Definition
double maximum( double x, double y, double z )
{
…
}
Function Definitions
 Example function
int square( int y )
{
return y * y;
}
 return keyword
 Returns data, and control goes to function’s caller
 If no data to return, use return;
 Function ends when reaches right brace
 Control goes to caller
 Functions cannot be defined inside other functions
Function Prototypes
 Function signature
 Part of prototype with name and parameters
 double maximum( double, double, double );
 Argument Coercion
 Force arguments to be of proper type
 Converting int (4) to double (4.0)
cout << sqrt(4)
 Conversion rules
 Arguments usually converted automatically
 Changing from double to int can truncate data
3.4 to 3
 Mixed type goes to highest type (promotion)
Function signature
Function Prototypes
Data types
long double
double
float
unsigned long int (synonymous with unsigned long)
long int (synonymous with long)
unsigned int (synonymous with unsigned)
int
unsigned short int (synonymous with unsigned short)
short int (synonymous with short)
unsigned char
char
bool (false becomes 0, true becomes 1)
Fig. 3.5 Promotion hierarc hy for built-in data types.
Header Files
 Header files contain
 Function prototypes
 Definitions of data types and constants
 Header files ending with .h
 Programmer-defined header files
#include “myheader.h”
 Library header files
#include <cmath>
Enumeration: enum
 Enumeration
 Set of integers with identifiers
enum typeName {constant1, constant2…};
 Constants start at 0 (default), incremented by 1
 Constants need unique names
 Cannot assign integer to enumeration variable
 Must use a previously defined enumeration type
 Example
enum Status {CONTINUE, WON, LOST};
Status enumVar;
enumVar = WON; // cannot do enumVar = 1
Storage Classes
 Variables have attributes
 Have seen name, type, size, value
 Storage class
 How long variable exists in memory
 Scope
 Where variable can be referenced in program
 Linkage
 For multiple-file program which files can use it
Storage Classes
 Automatic storage class
 Variable created when program enters its block
 Variable destroyed when program leaves block
 Only local variables of functions can be automatic
 Automatic by default
 keyword auto explicitly declares automatic
 register keyword
 Hint to place variable in high-speed register
 Good for often-used items (loop counters)
 Often unnecessary, compiler optimizes
 Specify either register or auto, not both
 register int counter = 1;
Storage Classes
 Static storage class
 Variables exist for entire program
 For functions, name exists for entire program
 May not be accessible, scope rules still apply
 auto and register keyword
 local variables in function
 register variables are kept in CPU registers
 static keyword
 Local variables in function
 Keeps value between function calls
 Only known in own function
 extern keyword
 Default for global variables/functions
 Globals: defined outside of a function block
 Known in any function that comes after it
Scope Rules
 Scope
 Portion of program where identifier can be used
 File scope
 Defined outside a function, known in all functions
 Global variables, function definitions and prototypes
 Function scope
 Can only be referenced inside defining function
 Only labels, e.g., identifiers with a colon (case:)
Scope Rules
 Block scope
 Begins at declaration, ends at right brace }
 Can only be referenced in this range
 Local variables, function parameters
 Local static variables still have block scope
 Storage class separate from scope
 Function-prototype scope
 Parameter list of prototype
 Names in prototype optional
 Compiler ignores
 In a single prototype, name can be used once
1 // Example 2
2 // A scoping example.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 void useLocal( void ); // function prototype
9 void useStaticLocal( void ); // function prototype
10 void useGlobal( void ); // function prototype
11
12 int x = 1; // global variable
13
14 int main()
15 {
16 int x = 5; // local variable to main
17
18 cout << "local x in main's outer scope is " << x << endl;
19
20 { // start new scope
21
22 int x = 7;
23
24 cout << "local x in main's inner scope is " << x << endl;
25
26 } // end new scope
Local/global? Scope?
Local/global? Scope?
Local/global? Scope?
43 // useLocal reinitializes local variable x during each call
44 void useLocal( void )
45 {
46 int x = 25; // initialized each time useLocal is called
47
48 cout << endl << "local x is " << x
49 << " on entering useLocal" << endl;
50 ++x;
51 cout << "local x is " << x
52 << " on exiting useLocal" << endl;
53
54 } // end function useLocal
55
Local/global? Scope?
56 // useStaticLocal initializes static local variable x only the
57 // first time the function is called; value of x is saved
58 // between calls to this function
59 void useStaticLocal( void )
60 {
61 // initialized only first time useStaticLocal is called
62 static int x = 50;
63
64 cout << endl << "local static x is " << x
65 << " on entering useStaticLocal" << endl;
66 ++x;
67 cout << "local static x is " << x
68 << " on exiting useStaticLocal" << endl;
69
70 } // end function useStaticLocal
71
Local/global? Scope?
Recursion
 Recursive functions
 Functions that call themselves
 Can only solve a base case
 If not base case
 Break problem into smaller problem(s)
 Launch new copy of function to work on the smaller problem (recursive call/recursive
step)
 Slowly converges towards base case
 Function makes call to itself inside the return statement
 Eventually base case gets solved
 Answer works way back up, solves entire problem
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)
Example Using Recursion:
Fibonacci Series
 Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
 Each number sum of two previous ones
 Example of a recursive formula:
 fib(n) = fib(n-1) + fib(n-2)
 C++ code for Fibonacci function
long fibonacci( long n )
{
if ???? // base case
return ???;
else
???
}
Example Using Recursion:
Fibonacci Series
 Order of operations
 return fibonacci( n - 1 ) + fibonacci( n - 2 );
 Recursive function calls
 Each level of recursion doubles the number of function calls
 30th number = 2^30 ~ 4 billion function calls
 Exponential complexity
f( 3 )
f( 1 )f( 2 )
f( 1 ) f( 0 ) return 1
return 1 return 0
return +
+return
Recursion vs. Iteration
 Repetition
 Iteration: explicit loop
 Recursion: repeated function calls
 Termination
 Iteration: loop condition fails
 Recursion: base case recognized
 Both can have infinite loops
 Balance between performance (iteration) and good software engineering (recursion)
Inline Functions
 Inline functions
 Keyword inline before function
 Asks the compiler to copy code into program instead of making function call
 Reduce function-call overhead
 Compiler can ignore inline
 Good for small, often-used functions
 Example
inline double cube( const double s )
{ return s * s * s; }
 const tells compiler that function does not modify s
References and Reference
Parameters
 Call by value
 Copy of data passed to function
 Changes to copy do not change original
 Prevent unwanted side effects
 Call by reference
 Function can directly access data
 Changes affect original
 Reference parameter
 Alias for argument in function call
 Passes parameter by reference
 Use & after data type in prototype
 void myFunction( int &data )
 Read “data is a reference to an int”
 Function call format the same
 However, original can now be changed
References and Reference
Parameters
 Pointers
 Another way to pass-by-refernce
 References as aliases to other variables
 Refer to same variable
 Can be used within a function
int count = 1; // declare integer variable count
int &cRef = count; // create cRef as an alias for count
++cRef; // increment count (using its alias)
 References must be initialized when declared
 Otherwise, compiler error
 Dangling reference
 Reference to undefined variable
Default Arguments
 Function call with omitted parameters
 If not enough parameters, rightmost go to their defaults
 Default values
 Can be constants, global variables, or function calls
 Set defaults in function prototype
int myFunction( int x = 1, int y = 2, int z = 3 );
 myFunction(3)
 x = 3, y and z get defaults (rightmost)
 myFunction(3, 5)
 x = 3, y = 5 and z gets default
Unitary Scope Resolution
Operator
 Unary scope resolution operator (::)
 Access global variable if local variable has same name
 Not needed if names are different
 Use ::variable
 y = ::x + 3;
 Good to avoid using same names for locals and globals
Function Overloading
 Function overloading
 Functions with same name and different parameters
 Should perform similar tasks
 i.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
 Overloaded functions distinguished by signature
 Based on name and parameter types (order matters)
 Name mangling
 Encode function identifier with no. and types of parameters
 Type-safe linkage
 Ensures proper overloaded function called
Function Templates
 Compact way to make overloaded functions
 Generate separate function for different data types
 Format
 Begin with keyword template
 Formal type parameters in brackets <>
 Every type parameter preceded by typename or class (synonyms)
 Placeholders for built-in types (i.e., int) or user-defined types
 Specify arguments types, return types, declare variables
 Function definition like normal, except formal types used
Function Templates
 Example
template < class T > // or template< typename T >
T square( T value1 )
{
return value1 * value1;
}
 T is a formal type, used as parameter type
 Above function returns variable of same type as parameter
 In function call, T replaced by real type
 If int, all T's become ints
int x;
int y = square(x);
1 // Example 3
2 // Using a function template.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 // definition of function template maximum
10 template < class T > // or template < typename T >
11 T maximum( T value1, T value2, T value3 )
12 {
13 T max = value1;
14
15 if ( value2 > max )
16 max = value2;
17
18 if ( value3 > max )
19 max = value3;
20
21 return max;
22
23 } // end function template maximum
24
Formal type parameter T
placeholder for type of data to
be tested by maximum.
maximum expects all
parameters to be of the same
type.
25 int main()
26 {
27 // demonstrate maximum with int values
28 int int1, int2, int3;
29
30 cout << "Input three integer values: ";
31 cin >> int1 >> int2 >> int3;
32
33 // invoke int version of maximum
34 cout << "The maximum integer value is: "
35 << maximum( int1, int2, int3 );
36
37 // demonstrate maximum with double values
38 double double1, double2, double3;
39
40 cout << "nnInput three double values: ";
41 cin >> double1 >> double2 >> double3;
42
43 // invoke double version of maximum
44 cout << "The maximum double value is: "
45 << maximum( double1, double2, double3 );
46
maximum called with various
data types.
47 // demonstrate maximum with char values
48 char char1, char2, char3;
49
50 cout << "nnInput three characters: ";
51 cin >> char1 >> char2 >> char3;
52
53 // invoke char version of maximum
54 cout << "The maximum character value is: "
55 << maximum( char1, char2, char3 )
56 << endl;
57
58 return 0; // indicates successful termination
59
60 } // end main
Input three integer values: 1 2 3
The maximum integer value is: 3
Input three double values: 3.3 2.2 1.1
The maximum double value is: 3.3
Input three characters: A C B
The maximum character value is: C
Arrays
 Array
 Consecutive group of memory locations
 Same name and type (int, char, etc.)
 To refer to an element
 Specify array name and position number (index)
 Format: arrayname[ position number ]
 First element at position 0
 N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
 Nth element as position N-1
Declaring Arrays
 When declaring arrays, specify
 Name
 Type of array
 Any data type
 Number of elements
 type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
 Declaring multiple arrays of same type
 Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];
Examples Using Arrays
 Initializing arrays
 For loop
 Set each element
 Initializer list
 Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
 If not enough initializers, rightmost elements 0
 If too many, syntax error
 To set every element to 0
int n[ 5 ] = { 0 };
 If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
 5 initializers, therefore 5 element array
 static int array[3]; ??
Examples Using Arrays
 Strings
 Arrays of characters
 All strings end with null ('0')
 Examples
 char string1[] = "hello";
Null character implicitly added
string1 has 6 elements
 char string1[] = { 'h', 'e', 'l', 'l', 'o', '0’ };
 Subscripting is the same
String1[ 0 ] is 'h'
string1[ 2 ] is 'l'
Examples Using Arrays
 Input from keyboard
char string2[ 10 ];
cin >> string2;
 Puts user input in string
 Stops at first whitespace character
 Adds null character
 If too much text entered, data written beyond array
 We want to avoid this
 Printing strings
 cout << string2 << endl;
 Does not work for other array types
 Characters printed until null found
Passing Arrays to Functions
 Specify name without brackets
 To pass array myArray to myFunction
int myArray[ 24 ];
myFunction( myArray, 24 );
 Array size usually passed, but not required
 Useful to iterate over all elements
 Arrays passed-by-reference
 Functions can modify original array data
 Value of name of array is address of first element
 Function knows where the array is stored
 Can change original memory locations
Passing Arrays to Functions
 Functions taking arrays
 Function prototype
 void modifyArray( int b[], int arraySize );
 void modifyArray( int [], int );
Names optional in prototype
 Both take an integer array and a single integer
 No need for array size between brackets
 Ignored by compiler
 If declare array parameter as const
 Cannot be modified (compiler error)
 void doNotModify( const int [] );
Sorting Arrays
 Example:
 Go left to right, and exchange elements as necessary
 One pass for each element
 Original: 3 4 2 7 6
 Pass 1: 3 2 4 6 7 (elements exchanged)
 Pass 2: 2 3 4 6 7
 Pass 3: 2 3 4 6 7 (no changes needed)
 Pass 4: 2 3 4 6 7
 Pass 5: 2 3 4 6 7
 Small elements "bubble" to the top (like 2 in this example)
Multiple-Subscripted Arrays
Multiple subscripts
a[ i ][ j ]
Tables with rows and columns
Specify row, then column
“Array of arrays”
 a[0] is an array of 4 elements
 a[0][0] is the first element of
that array
Row 0
Row 1
Row 2
Column 0 Column 1 Column 2 Column 3
a[ 0 ][ 0 ]
a[ 1 ][ 0 ]
a[ 2 ][ 0 ]
a[ 0 ][ 1 ]
a[ 1 ][ 1 ]
a[ 2 ][ 1 ]
a[ 0 ][ 2 ]
a[ 1 ][ 2 ]
a[ 2 ][ 2 ]
a[ 0 ][ 3 ]
a[ 1 ][ 3 ]
a[ 2 ][ 3 ]
Row subscript
Array name
Column subscript
To initialize
Default of 0
Initializers grouped by row in
braces
int b[ 2 ][ 2 ]={ { 1, 2 }, { 3, 4 } };
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Pointer
 Pointer variables
 Contain memory addresses as values
 Normally, variable contains specific value (direct reference)
 Pointers contain address of variable that has specific value (indirect reference)
 Indirection
 Referencing value through pointer
 Pointer declarations
 * indicates variable is pointer
int *myPtr;
declares pointer to int, pointer of type int *
 Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;
count
7
countPtr count
7
Pointer Variable Declarations and Initialization
Pointer Operators
 & (address operator)
 Returns memory address of its
operand
 Example
int y = 5;
int *yPtr;
yPtr = &y;
yPtr
y
5
yptr
500000 600000
y
600000 5
address of y
is value of
yptr
yPtr “points to” y
* - indirection/
dereferencing operator)
*yPtr returns y
dereferenced pointer is
lvalue
*yptr = 9 ??
Calling Functions by Reference
 3 ways to pass arguments to function
 Pass-by-value
 Pass-by-reference with reference arguments
 Pass-by-reference with pointer arguments
 Arguments passed to function using reference arguments
 Modify original values of arguments
 More than one value “returned”
int Cube(int *x) { …}
Function call: Cube(&a)
Using const with Pointers
const qualifier
Value of variable should not be modified
const used when function does not need to change a variable
Principle of least privilege
const pointers
Always point to same memory location
Default for array name
Must be initialized when declared
Four ways to pass pointer to function
Nonconstant pointer to nonconstant data
 Highest amount of access
Nonconstant pointer to constant data
Constant pointer to nonconstant data
Constant pointer to constant data
 Least amount of access
1 // Example 3
2 // Attempting to modify a constant pointer to
3 // non-constant data.
4
5 int main()
6 {
7 int x, y;
8
9 // ptr is a constant pointer to an integer that can
10 // be modified through ptr, but ptr always points to the
11 // same memory location.
12 int * const ptr = &x;
13
14 *ptr = 7; // allowed: *ptr is not const
15 ptr = &y; // error: ptr is const; cannot assign new address
16
17 return 0; // indicates successful termination
18
19 } // end main
d:cpphtp4_examplesch05Fig05_13.cpp(15) : error C2166:
l-value specifies const object
ptr is constant pointer to
integer.Can modify x (pointed to by
ptr) since x not constant.Cannot modify ptr to point
to new address since ptr is
constant.
Line 15 generates compiler
error by attempting to assign
new address to constant
pointer.
1 // Example 4
2 // Attempting to modify a constant pointer to constant data.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 int x = 5, y;
11
12 // ptr is a constant pointer to a constant integer.
13 // ptr always points to the same location; the integer
14 // at that location cannot be modified.
15 const int *const ptr = &x;
16
17 cout << *ptr << endl;
18
19 *ptr = 7; // error: *ptr is const; cannot assign new value
20 ptr = &y; // error: ptr is const; cannot assign new address
21
22 return 0; // indicates successful termination
23
24 } // end main
ptr is constant pointer to
integer constant.
Cannot modify x (pointed to
by ptr) since *ptr declared
constant.
Cannot modify ptr to point
to new address since ptr is
constant.
Pointer Expressions and Pointer
Arithmetic
Pointer arithmetic
 Increment/decrement pointer (++ or --)
 Add/subtract an integer to/from a pointer( + or += , - or -=)
 Pointers may be subtracted from each other
 Pointer arithmetic meaningless unless performed on pointer to array
5 element int array on a machine using 4 byte ints
 vPtr points to first element v[ 0 ], which is at location 3000
vPtr = 3000
 vPtr += 2; sets vPtr to 3008
vPtr points to v[ 2 ]
pointer variable vPtr
v[0] v[1] v[2] v[4]v[3]
3000 3004 3008 3012 3016
location
Pointer Expressions and Pointer
Arithmetic
 Subtracting pointers
 Returns number of elements between two addresses
vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
vPtr2 - vPtr == 2
 Pointer assignment
 Pointer can be assigned to another pointer if both of same type
 If not same type, cast operator must be used
 Exception: pointer to void (type void *)
 Generic pointer, represents any type
 No casting needed to convert pointer to void pointer
 void pointers cannot be dereferenced
Pointer Expressions and Pointer
Arithmetic
 Pointer comparison
 Use equality and relational operators
 Comparisons meaningless unless pointers point to members of same array
 Compare addresses stored in pointers
 Example: could show that one pointer points to higher numbered element of array
than other pointer
 Common use to determine whether pointer is 0 (does not point to anything)
Relationship Between Pointers
and Arrays
 Arrays and pointers closely related
 Array name like constant pointer
 Pointers can do array subscripting operations
 Accessing array elements with pointers
 Element b[ n ] can be accessed by *( bPtr + n )
 Called pointer/offset notation
 Addresses
 &b[ 3 ] same as bPtr + 3
 Array name can be treated as pointer
 b[ 3 ] same as *( b + 3 )
 Pointers can be subscripted (pointer/subscript notation)
 bPtr[ 3 ] same as b[ 3 ]
Arrays of Pointers
 Arrays can contain pointers
 Commonly used to store array of strings
char *suit[ 4 ] = {"Hearts", "Diamonds",
"Clubs", "Spades" };
 Each element of suit points to char * (a string)
 Array does not store strings, only pointers to strings
 suit array has fixed size, but strings can be of any size
suit[3]
suit[2]
suit[1]
suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’0’
’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’0’
’C’ ’l’ ’u’ ’b’ ’s’ ’0’
’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’0’
Function Pointers
 Calling functions using pointers
 Assume parameter:
 bool ( *compare ) ( int, int )
 Execute function with either
 ( *compare ) ( int1, int2 )
Dereference pointer to function to execute
OR
 compare( int1, int2 )
Could be confusing
 User may think compare name of actual function in program
1 // Example 5
2 // Multipurpose sorting program using function pointers.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 #include <iomanip>
10
11 using std::setw;
12
13 // prototypes
14 void bubble( int [], const int, bool (*)( int, int ) );
15 void swap( int * const, int * const );
16 bool ascending( int, int );
17 bool descending( int, int );
18
19 int main()
20 {
21 const int arraySize = 10;
22 int order;
23 int counter;
24 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
25
Parameter is pointer to
function that receives two
integer parameters and returns
bool result.
26 cout << "Enter 1 to sort in ascending order,n"
27 << "Enter 2 to sort in descending order: ";
28 cin >> order;
29 cout << "nData items in original ordern";
30
31 // output original array
32 for ( counter = 0; counter < arraySize; counter++ )
33 cout << setw( 4 ) << a[ counter ];
34
35 // sort array in ascending order; pass function ascending
36 // as an argument to specify ascending sorting order
37 if ( order == 1 ) {
38 bubble( a, arraySize, ascending );
39 cout << "nData items in ascending ordern";
40 }
41
42 // sort array in descending order; pass function descending
43 // as an agrument to specify descending sorting order
44 else {
45 bubble( a, arraySize, descending );
46 cout << "nData items in descending ordern";
47 }
48
49 // output sorted array
50 for ( counter = 0; counter < arraySize; counter++ )
51 cout << setw( 4 ) << a[ counter ];
52
53 cout << endl;
54
55 return 0; // indicates successful termination
56
57 } // end main
58
59 // multipurpose bubble sort; parameter compare is a pointer to
60 // the comparison function that determines sorting order
61 void bubble( int work[], const int size,
62 bool (*compare)( int, int ) )
63 {
64 // loop to control passes
65 for ( int pass = 1; pass < size; pass++ )
66
67 // loop to control number of comparisons per pass
68 for ( int count = 0; count < size - 1; count++ )
69
70 // if adjacent elements are out of order, swap them
71 if ( (*compare)( work[ count ], work[ count + 1 ] ) )
72 swap( &work[ count ], &work[ count + 1 ] );
compare is pointer to
function that receives two
integer parameters and returns
bool result.
Parentheses necessary to
indicate pointer to function
Call passed function
compare; dereference
pointer to execute function.
73
74 } // end function bubble
75
76 // swap values at memory locations to which
77 // element1Ptr and element2Ptr point
78 void swap( int * const element1Ptr, int * const element2Ptr )
79 {
80 int hold = *element1Ptr;
81 *element1Ptr = *element2Ptr;
82 *element2Ptr = hold;
83
84 } // end function swap
85
86 // determine whether elements are out of order
87 // for an ascending order sort
88 bool ascending( int a, int b )
89 {
90 return b < a; // swap if b is less than a
91
92 } // end function ascending
93
94 // determine whether elements are out of order
95 // for a descending order sort
96 bool descending( int a, int b )
97 {
98 return b > a; // swap if b is greater than a
99
100 } // end function descending
Enter 1 to sort in ascending order,
Enter 2 to sort in descending order: 1
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89
Enter 1 to sort in ascending order,
Enter 2 to sort in descending order: 2
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in descending order
89 68 45 37 12 10 8 6 4 2
Function Pointers
 Arrays of pointers to functions
 Menu-driven systems
 Pointers to each function stored in array of pointers to functions
 All functions must have same return type and same parameter types
 Menu choice  subscript into array of function pointers
1 // Example 6
2 // Demonstrating an array of pointers to functions.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 // function prototypes
10 void function1( int );
11 void function2( int );
12 void function3( int );
13
14 int main()
15 {
16 // initialize array of 3 pointers to functions that each
17 // take an int argument and return void
18 void (*f[ 3 ])( int ) = { function1, function2, function3 };
19
20 int choice;
21
22 cout << "Enter a number between 0 and 2, 3 to end: ";
23 cin >> choice;
24
Array initialized with names
of three functions; function
names are pointers.
25 // process user's choice
26 while ( choice >= 0 && choice < 3 ) {
27
28 // invoke function at location choice in array f
29 // and pass choice as an argument
30 (*f[ choice ])( choice );
31
32 cout << "Enter a number between 0 and 2, 3 to end: ";
33 cin >> choice;
34 }
35
36 cout << "Program execution completed." << endl;
37
38 return 0; // indicates successful termination
39
40 } // end main
41
42 void function1( int a )
43 {
44 cout << "You entered " << a
45 << " so function1 was callednn";
46
47 } // end function1
48
Call chosen function by
dereferencing corresponding
element in array.
25 // process user's choice
26 while ( choice >= 0 && choice < 3 ) {
27
28 // invoke function at location choice in array f
29 // and pass choice as an argument
30 (*f[ choice ])( choice );
31
32 cout << "Enter a number between 0 and 2, 3 to end: ";
33 cin >> choice;
34 }
35
36 cout << "Program execution completed." << endl;
37
38 return 0; // indicates successful termination
39
40 } // end main
41
42 void function1( int a )
43 {
44 cout << "You entered " << a
45 << " so function1 was callednn";
46
47 } // end function1
48
Call chosen function by
dereferencing corresponding
element in array.
Fundamentals of Characters and
Strings
 Character constant
 Integer value represented as character in single quotes
 'z' is integer value of z
 122 in ASCII
 String
 Series of characters treated as single unit
 Can include letters, digits, special characters +, -, * ...
 String literal (string constants)
 Enclosed in double quotes, for example:
"I like C++"
 Array of characters, ends with null character '0'
 String is constant pointer
 Pointer to string’s first character
Like arrays
Fundamentals of Characters and Strings
 String assignment
 Character array
 char color[] = "blue";
Creates 5 element char array color
 last element is '0'
 Variable of type char *
 char *colorPtr = "blue";
Creates pointer colorPtr to letter b in string “blue”
 “blue” somewhere in memory
 Alternative for character array
 char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘0’ };
Fundamentals of Characters and Strings
 Reading strings
 Assign input to character array word[ 20 ]
cin >> word
 Reads characters until whitespace or EOF
 String could exceed array size
cin >> setw( 20 ) >> word;
 Reads 19 characters (space reserved for '0')
Fundamentals of Characters and Strings
 cin.getline
 Read line of text
 cin.getline( array, size, delimiter );
 Copies input into specified array until either
 One less than size is reached
 delimiter character is input
 Example
char sentence[ 80 ];
cin.getline( sentence, 80, 'n' );
String Manipulation Functions of the String-
handling Library
 String handling library <cstring> provides functions to
 Manipulate string data
 Compare strings
 Search strings for characters and other strings
 Tokenize strings (separate strings into logical pieces)
String Manipulation Functions of the String-
handling Library
char *strcpy( char *s1,
const char *s2 );
Copies the string s2 into the character
array s1. The value of s1 is returned.
char *strncpy( char *s1,
const char *s2, size_t n );
Copies at most n characters of the string
s2 into the character array s1. The value
of s1 is returned.
char *strcat( char *s1,
const char *s2 );
Appends the string s2 to the string s1. The
first character of s2 overwrites the
terminating null character of s1. The value
of s1 is returned.
char *strncat( char *s1,
const char *s2, size_t n );
Appends at most n characters of string s2
to string s1. The first character of s2
overwrites the terminating null character of
s1. The value of s1 is returned.
int strcmp( const char *s1,
const char *s2 );
Compares the string s1 with the string s2.
The function returns a value of zero, less
than zero or greater than zero if s1 is
equal to, less than or greater than s2,
respectively.
String Manipulation Functions of the
String-handling Library
int strncmp( const char *s1,
const char *s2, size_t n );
Compares up to n characters of the
string s1 with the string s2. The
function returns zero, less than zero or
greater than zero if s1 is equal to, less
than or greater than s2, respectively.
char *strtok( char *s1, const
char *s2 );
A sequence of calls to strtok breaks
string s1 into “tokens”—logical pieces
such as words in a line of text—
delimited by characters contained in
string s2. The first call contains s1 as
the first argument, and subsequent calls
to continue tokenizing the same string
contain NULL as the first argument. A
pointer to the current token is returned
by each call. If there are no more
tokens when the function is called,
NULL is returned.
size_t strlen( const char *s ); Determines the length of string s. The
number of characters preceding the
terminating null character is returned.
Structure Definitions
 Structures
 Aggregate data types built using elements of other types
struct Time {
int hour;
int minute;
int second;
};
Structure member naming
 In same struct: must have unique names
 In different structs: can share name
struct definition must end with semicolon
Structure tag
Structure members
Structure
Structure Definitions
 Self-referential structure
 Structure member cannot be instance of enclosing struct
 Structure member can be pointer to instance of enclosing struct (self-referential
structure)
 Used for linked lists, queues, stacks and trees
 struct definition
 Creates new data type used to declare variables
 Structure variables declared like variables of other types
 Examples:
 Time timeObject;
 Time timeArray[ 10 ];
 Time *timePtr;
 Time &timeRef = timeObject;
Accessing Structure Members
 Member access operators
 Dot operator (.) for structure and class members
 Arrow operator (->) for structure and class members via pointer to object
 Print member hour of timeObject:
cout << timeObject.hour;
OR
timePtr = &timeObject;
cout << timePtr->hour;
 timePtr->hour same as ( *timePtr ).hour
 Parentheses required
* lower precedence than .
Implementing a User-Defined
Type Time with a struct
 Default: structures passed by value
 Pass structure by reference
 Avoid overhead of copying structure
 C-style structures
 No “interface”
 If implementation changes, all programs using that struct must change
accordingly
 Cannot print as unit
 Must print/format member by member
 Cannot compare in entirety
 Must compare member by member
1 // Example 7
2 // Create a structure, set its members, and print it.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setfill;
11 using std::setw;
12
13 // structure definition
14 struct Time {
15 int hour; // 0-23 (24-hour clock format)
16 int minute; // 0-59
17 int second; // 0-59
18
19 }; // end struct Time
20
21 void printUniversal( const Time & ); // prototype
22 void printStandard( const Time & ); // prototype
23
Define structure type Time
with three integer members.
Pass references to constant
Time objects to eliminate
copying overhead.
Class
 Classes(keyword class)
 Model objects
 Attributes (data members)
 Behaviors (member functions)
Methods
Invoked in response to messages
 Member access specifiers: public, Private, protected:
 Constructor function
 Special member function
 Initializes data members
 Same name as class
 Called when object instantiated
 Several constructors
 Function overloading
 No return type
Implementing a Time Abstract Data
Type with a class
 Objects of class
 After class definition
 Class name new type specifier
 Object, array, pointer and
reference declarations
Member functions defined
outside class
Time sunset; // object of type Time
Time arrayOfTimes[ 5 ]; // array of Time objects
Time *pointerToTime; // pointer to a Time object
Time &dinnerTime = sunset; // reference to a Time object
Class name becomes
new type specifier.
Binary scope resolution (::)
ReturnType ClassName::MemberFunctionName(
){…}
Member functions defined inside class
Do not need scope resolution
operator, class name
Compiler attempts inline
Outside class, inline explicitly with
keyword inline
1 // Example 8
2 // Time class.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setfill;
11 using std::setw;
12
13 // Time abstract data type (ADT) definition
14 class Time {
15
16 public:
17 Time(); // constructor
18 void setTime( int, int, int ); // set hour, minute, second
19 void printUniversal(); // print universal-time format
20 void printStandard(); // print standard-time format
21
Define class Time.
22 private:
23 int hour; // 0 - 23 (24-hour clock format)
24 int minute; // 0 - 59
25 int second; // 0 - 59
26
27 }; // end class Time
28
29 // Time constructor initializes each data member to zero and
30 // ensures all Time objects start in a consistent state
31 Time::Time()
32 {
33 hour = minute = second = 0;
34
35 } // end Time constructor
36
37 // set new Time value using universal time, perform validity
38 // checks on the data values and set invalid values to zero
39 void Time::setTime( int h, int m, int s )
40 {
41 hour = ( h >= 0 && h < 24 ) ? h : 0;
42 minute = ( m >= 0 && m < 60 ) ? m : 0;
43 second = ( s >= 0 && s < 60 ) ? s : 0;
44
45 } // end function setTime
46
Constructor initializes
private data members
to 0.
public member
function checks
parameter values for
validity before setting
private data
members.
47 // print Time in universal format
48 void Time::printUniversal()
49 {
50 cout << setfill( '0' ) << setw( 2 ) << hour << ":"
51 << setw( 2 ) << minute << ":"
52 << setw( 2 ) << second;
53
54 } // end function printUniversal
55
56 // print Time in standard format
57 void Time::printStandard()
58 {
59 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
60 << ":" << setfill( '0' ) << setw( 2 ) << minute
61 << ":" << setw( 2 ) << second
62 << ( hour < 12 ? " AM" : " PM" );
63
64 } // end function printStandard
65
66 int main()
67 {
68 Time t; // instantiate object t of class Time
69
Declare variable t to be
object of class Time.
No arguments (implicitly
“know” purpose is to print
data members); member
function calls more concise.
70 // output Time object t's initial values
71 cout << "The initial universal time is ";
72 t.printUniversal(); // 00:00:00
73
74 cout << "nThe initial standard time is ";
75 t.printStandard(); // 12:00:00 AM
76
77 t.setTime( 13, 27, 6 ); // change time
78
79 // output Time object t's new values
80 cout << "nnUniversal time after setTime is ";
81 t.printUniversal(); // 13:27:06
82
83 cout << "nStandard time after setTime is ";
84 t.printStandard(); // 1:27:06 PM
85
86 t.setTime( 99, 99, 99 ); // attempt invalid settings
87
88 // output t's values after specifying invalid values
89 cout << "nnAfter attempting invalid settings:"
90 << "nUniversal time: ";
91 t.printUniversal(); // 00:00:00
92
Invoke public member
functions to print time.
Set data members using
public member function.
Attempt to set data members
to invalid values using
public member function.
93 cout << "nStandard time: ";
94 t.printStandard(); // 12:00:00 AM
95 cout << endl;
96
97 return 0;
98
99 } // end main
The initial universal time is 00:00:00
The initial standard time is 12:00:00 AM
Universal time after setTime is 13:27:06
Standard time after setTime is 1:27:06 PM
After attempting invalid settings:
Universal time: 00:00:00
Standard time: 12:00:00 AM
Data members set to 0 after
attempting invalid settings.
Classes
 Destructors
 Same name as class
 Preceded with tilde (~)
 No arguments
 Cannot be overloaded
 Performs “termination housekeeping”
 Advantages of using classes
 Simplify programming
 Interfaces
 Hide implementation
 Software reuse
 Composition (aggregation)
Class objects included as members of other classes
 Inheritance
New classes derived from old
Class Scope and Accessing Class
Members
 Class scope
 Data members, member functions
 Within class scope
 Class members
Immediately accessible by all member functions
Referenced by name
 Outside class scope
 Referenced through handles
Object name, reference to object, pointer to object
 File scope
 Nonmember functions
Class Scope and Accessing Class
Members
Function scope
Variables declared in member function
Only known to function
Variables with same name as class-scope variables
 Class-scope variable “hidden”
Access with scope resolution operator (::)
ClassName::classVariableName
Variables only known to function they are defined in
Variables are destroyed after function completion
Operators to access class members
Identical to those for structs
Dot member selection operator (.)
 Object
 Reference to object
Arrow member selection operator (->)
 Pointers
1 // Example 9
2 // Demonstrating the class member access operators . and ->
3 //
4 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA!
5 #include <iostream>
6
7 using std::cout;
8 using std::endl;
9
10 // class Count definition
11 class Count {
12
13 public:
14 int x;
15
16 void print()
17 {
18 cout << x << endl;
19 }
20
21 }; // end class Count
22
Data member x public to
illustrate class member access
operators; typically data
members private.
Separating Interface from
Implementation
Separating interface from implementation
Advantage: Easier to modify programs
Disadvantage
 Header files
Portions of implementation: Inline member functions
Hints about other implementation: private members
 Can hide more with proxy class
Header files
Class definitions and function prototypes
Included in each file using class
 #include
File extension .h
Source-code files
Member function definitions
Same base name
 Convention
Compiled and linked
Controlling Access to Members
 Access modes
 private
 Default access mode
 Accessible to member functions and friends
 public
 Accessible to any function in program with handle to class object
 protected (later)
 Class member access
 Default private
 Explicitly set to private, public, protected
 struct member access
 Default public
 Explicitly set to private, public, protected
Access Functions and Utility
Functions
 Access to class’s private data
 Controlled with access functions (accessor methods)
 Get function - Read private data
 Set function - Modify private data
 Access functions
 public
 Read/display data
 Predicate functions
 Check conditions
 Utility functions (helper functions)
 private
 Support operation of public member functions
 Not intended for direct client use
1 // Example 10
2 // SalesPerson class definition.
3 // Member functions defined in salesp.cpp.
4 #ifndef SALESP_H
5 #define SALESP_H
6
7 class SalesPerson {
8
9 public:
10 SalesPerson(); // constructor
11 void getSalesFromUser(); // input sales from keyboard
12 void setSales( int, double ); // set sales for a month
13 void printAnnualSales(); // summarize and print sales
14
15 private:
16 double totalAnnualSales(); // utility function
17 double sales[ 12 ]; // 12 monthly sales figures
18
19 }; // end class SalesPerson
20
21 #endif
Set access function
performs validity
checks.
private utility
function.
25 // get 12 sales figures from the user at the keyboard
26 void SalesPerson::getSalesFromUser()
27 {
28 double salesFigure;
29
30 for ( int i = 1; i <= 12; i++ ) {
31 cout << "Enter sales amount for month " << i << ": ";
32 cin >> salesFigure;
33 setSales( i, salesFigure );
34
35 } // end for
36
37 } // end function getSalesFromUser
38
39 // set one of the 12 monthly sales figures; function subtracts
40 // one from month value for proper subscript in sales array
41 void SalesPerson::setSales( int month, double amount )
42 {
43 // test for valid month and amount values
44 if ( month >= 1 && month <= 12 && amount > 0 )
45 sales[ month - 1 ] = amount; // adjust for subscripts 0-11
46
47 else // invalid month or amount value
48 cout << "Invalid month or sales figure" << endl;
Set access function performs
validity checks.
Initializing Class Objects:
Constructors
Constructors
Initialize data members; no return type
 Or can set later
Same name as class
Can specify default arguments
Default constructors
 Defaults all arguments
OR
 Explicitly requires no arguments
 Can be invoked with no arguments
 Only one per class
Initializers
Passed as arguments to constructor
In parentheses to right of class name before semicolon
Class-type ObjectName( value1,value2,…);
1 // Example 11
2 // Declaration of class Time.
3 // Member functions defined in time2.cpp.
4
5 // prevent multiple inclusions of header file
6 #ifndef TIME2_H
7 #define TIME2_H
8
9 // Time abstract data type definition
10 class Time {
11
12 public:
13 Time( int = 0, int = 0, int = 0); // default constructor
14 void setTime( int, int, int ); // set hour, minute, second
15 void printUniversal(); // print universal-time format
16 void printStandard(); // print standard-time format
17
18 private:
19 int hour; // 0 - 23 (24-hour clock format)
20 int minute; // 0 - 59
21 int second; // 0 - 59
22
23 }; // end class Time
24
25 #endif
Default constructor specifying
all arguments.
1 // Example 12
2 // Member-function definitions for class Time.
3 #include <iostream>
4
5 using std::cout;
6
7 #include <iomanip>
8
9 using std::setfill;
10 using std::setw;
11
12 // include definition of class Time from time2.h
13 #include "time2.h"
14
15 // Time constructor initializes each data member to zero;
16 // ensures all Time objects start in a consistent state
17 Time::Time( int hr, int min, int sec )
18 {
19 setTime( hr, min, sec ); // validate and set time
20
21 } // end Time constructor
22
Constructor calls setTime
to validate passed (or default)
values.
23 // set new Time value using universal time, perform validity
24 // checks on the data values and set invalid values to zero
25 void Time::setTime( int h, int m, int s )
26 {
27 hour = ( h >= 0 && h < 24 ) ? h : 0;
28 minute = ( m >= 0 && m < 60 ) ? m : 0;
29 second = ( s >= 0 && s < 60 ) ? s : 0;
30
31 } // end function setTime
32
33 // print Time in universal format
34 void Time::printUniversal()
35 {
36 cout << setfill( '0' ) << setw( 2 ) << hour << ":"
37 << setw( 2 ) << minute << ":"
38 << setw( 2 ) << second;
39
40 } // end function printUniversal
41
1 // Example 13
2 // Demonstrating a default constructor for class Time.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // include definition of class Time from time2.h
9 #include "time2.h"
10
11 int main()
12 {
13 Time t1; // all arguments defaulted
14 Time t2( 2 ); // minute and second defaulted
15 Time t3( 21, 34 ); // second defaulted
16 Time t4( 12, 25, 42 ); // all values specified
17 Time t5( 27, 74, 99 ); // all bad values specified
18
19 cout << "Constructed with:nn"
20 << "all default arguments:n ";
21 t1.printUniversal(); // 00:00:00
22 cout << "n ";
23 t1.printStandard(); // 12:00:00 AM
24
Initialize Time
objects using
default arguments.
Initialize Time object with
invalid values; validity
checking will set values to 0.
25 cout << "nnhour specified; default minute and second:n ";
26 t2.printUniversal(); // 02:00:00
27 cout << "n ";
28 t2.printStandard(); // 2:00:00 AM
29
30 cout << "nnhour and minute specified; default second:n ";
31 t3.printUniversal(); // 21:34:00
32 cout << "n ";
33 t3.printStandard(); // 9:34:00 PM
34
35 cout << "nnhour, minute, and second specified:n ";
36 t4.printUniversal(); // 12:25:42
37 cout << "n ";
38 t4.printStandard(); // 12:25:42 PM
39
40 cout << "nnall invalid values specified:n ";
41 t5.printUniversal(); // 00:00:00
42 cout << "n ";
43 t5.printStandard(); // 12:00:00 AM
44 cout << endl;
45
46 return 0;
47
48 } // end main
t5 constructed with invalid
arguments; values set to 0.
Destructors
 Destructors
 Special member function
 Same name as class preceded with tilde (~)
 No arguments; No return value
 Cannot be overloaded
 Performs “termination housekeeping”
 Before system reclaims object’s memory
Reuse memory for new objects
 No explicit destructor
 Compiler creates “empty destructor”
 Constructors and destructors - Called implicitly by compiler
 Order of function calls
 Depends on when execution enters and exits scope of objects
 Generally, destructor calls reverse order of constructor calls
When Constructors and
Destructors Are Called
 Global scope objects
 Constructors - Before any other function (including main)
 Destructors
When main terminates (or exit function called)
Not called if program terminates with abort
 Automatic local objects
 Constructors - When objects defined & each time execution enters scope
 Destructors
When objects leave scope
 Execution exits block in which object defined
Not called if program ends with exit or abort
 static local objects
 Constructors
Exactly once
When execution reaches point where object defined
 Destructors
When main terminates or exit function called
Not called if program ends with abort
1 // Example 14
2 // Demonstrating the order in which constructors and
3 // destructors are called.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 // include CreateAndDestroy class definition from create.h
10 #include "create.h"
11
12 void create( void ); // prototype
13
14 // global object
15 CreateAndDestroy first( 1, "(global before main)" );
16
17 int main()
18 {
19 cout << "nMAIN FUNCTION: EXECUTION BEGINS" << endl;
20
21 CreateAndDestroy second( 2, "(local automatic in main)" );
22
23 static CreateAndDestroy third(
24 3, "(local static in main)" );
25
Create variable with global
scope.
Create local automatic object.
Create static local object.
26 create(); // call function to create objects
27
28 cout << "nMAIN FUNCTION: EXECUTION RESUMES" << endl;
29
30 CreateAndDestroy fourth( 4, "(local automatic in main)" );
31
32 cout << "nMAIN FUNCTION: EXECUTION ENDS" << endl;
33
34 return 0;
35
36 } // end main
37
38 // function to create objects
39 void create( void )
40 {
41 cout << "nCREATE FUNCTION: EXECUTION BEGINS" << endl;
42
43 CreateAndDestroy fifth( 5, "(local automatic in create)" );
44
45 static CreateAndDestroy sixth(
46 6, "(local static in create)" );
47
48 CreateAndDestroy seventh(
49 7, "(local automatic in create)" );
50 cout << "nCREATE FUNCTION: EXECUTION ENDS" << endl;
52
53 } // end function create
Create local automatic
objects.
Create local automatic object.
Create local automatic object
in function.
Create static local object
in function.
Create local automatic object
in function.
Object 1 constructor runs (global before main)
MAIN FUNCTION: EXECUTION BEGINS
Object 2 constructor runs (local automatic in main)
Object 3 constructor runs (local static in main)
CREATE FUNCTION: EXECUTION BEGINS
Object 5 constructor runs (local automatic in create)
Object 6 constructor runs (local static in create)
Object 7 constructor runs (local automatic in create)
CREATE FUNCTION: EXECUTION ENDS
Object 7 destructor runs (local automatic in create)
Object 5 destructor runs (local automatic in create)
MAIN FUNCTION: EXECUTION RESUMES
Object 4 constructor runs (local automatic in main)
MAIN FUNCTION: EXECUTION ENDS
Object 4 destructor runs (local automatic in main)
Object 2 destructor runs (local automatic in main)
Object 6 destructor runs (local static in create)
Object 3 destructor runs (local static in main)
Object 1 destructor runs (global before main)
Destructors for local
automatic objects in main
called in reverse order of
constructors.
Local static object exists
until program termination.Global object constructed
before main execution and
destroyed last.
Local automatic objects
destroyed after function
execution ends in reverse
order of construction.
Local static object
constructed on first function
call and destroyed after main
execution ends.
Using Set and Get Functions
 Set functions
 Perform validity checks before modifying private data
 Notify if invalid values
 Indicate with return values
 Get functions
 “Query” functions
 Control format of data returned
Subtle Trap: Returning a Reference to a
private Data Member
 Reference to object
 &pRef = p;
 Alias for name of object
 Lvalue
 Can receive value in assignment statement
Changes original object
 Returning references
 public member functions can return non-const references to private data
members
 Client able to modify private data members
1 // Example 15
2 // Declaration of class Time.
3 // Member functions defined in time4.cpp
4
5 // prevent multiple inclusions of header file
6 #ifndef TIME4_H
7 #define TIME4_H
8
9 class Time {
10
11 public:
12 Time( int = 0, int = 0, int = 0 );
13 void setTime( int, int, int );
14 int getHour();
15
16 int &badSetHour( int ); // DANGEROUS reference return
17
18 private:
19 int hour;
20 int minute;
21 int second;
22
23 }; // end class Time
24
25 #endif
Function to demonstrate
effects of returning reference
to private data member.
25 // return hour value
26 int Time::getHour()
27 {
28 return hour;
29
30 } // end function getHour
31
32 // POOR PROGRAMMING PRACTICE:
33 // Returning a reference to a private data member.
34 int &Time::badSetHour( int hh )
35 {
36 hour = ( hh >= 0 && hh < 24 ) ? hh : 0;
37
38 return hour; // DANGEROUS reference return
39
40 } // end function badSetHour
Return reference to private
data member hour.
1 // Example 16
2 // Demonstrating a public member function that
3 // returns a reference to a private data member.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 // include definition of class Time from time4.h
10 #include "time4.h"
11
12 int main()
13 {
14 Time t;
15
16 // store in hourRef the reference returned by badSetHour
17 int &hourRef = t.badSetHour( 20 );
18
19 cout << "Hour before modification: " << hourRef;
20
21 // use hourRef to set invalid value in Time object t
22 hourRef = 30;
23
24 cout << "nHour after modification: " << t.getHour();
25
badSetHour returns
reference to private data
member hour.
Reference allows setting of
private data member
hour.
26 // Dangerous: Function call that returns
27 // a reference can be used as an lvalue!
28 t.badSetHour( 12 ) = 74;
29
30 cout << "nn*********************************n"
31 << "POOR PROGRAMMING PRACTICE!!!!!!!!n"
32 << "badSetHour as an lvalue, Hour: "
33 << t.getHour()
34 << "n*********************************" << endl;
35
36 return 0;
37
38 } // end main
Hour before modification: 20
Hour after modification: 30
*********************************
POOR PROGRAMMING PRACTICE!!!!!!!!
badSetHour as an lvalue, Hour: 74
*********************************
Can use function call as
lvalue to set invalid value.
Returning reference allowed
invalid setting of private
data member hour.
Default Memberwise
Assignment
 Assigning objects
 Assignment operator (=)
 Can assign one object to another of same type
 Default: memberwise assignment
Each right member assigned individually to left member
 Passing, returning objects
 Objects passed as function arguments
 Objects returned from functions
 Default: pass-by-value
 Copy of object passed, returned
Copy constructor
 Copy original values into new object
1 // Example 17
2 // Demonstrating that class objects can be assigned
3 // to each other using default memberwise assignment.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 // class Date definition
10 class Date {
11
12 public:
13 Date( int = 1, int = 1, int = 1990 ); // default constructor
14 void print();
15
16 private:
17 int month;
18 int day;
19 int year;
20
21 }; // end class Date
22
Software Reusability
 Software reusability
 Class libraries
 Well-defined
 Carefully tested
 Well-documented
 Portable
 Widely available
 Speeds development of powerful, high-quality software
 Rapid applications development (RAD)
 Resulting problems
 Cataloging schemes
 Licensing schemes
 Protection mechanisms
const (Constant) Objects and
const Member Functions
 Keyword const
 Specify object not modifiable
 Compiler error if attempt to modify const object
 Example
const Time noon( 12, 0, 0 );
 Declares const object noon of class Time
 Initializes to 12
 const member functions
 Member functions for const objects must also be const
 Cannot modify object
 Specify const in both prototype and definition
 Prototype
After parameter list
 Definition
Before beginning left brace
const (Constant) Objects and
const Member Functions
 Constructors and destructors
 Cannot be const
 Must be able to modify objects
 Constructor
Initializes objects
 Destructor
Performs termination housekeeping
 Member initializer syntax
 Initializing with member initializer syntax
 Can be used for
All data members
 Must be used for
const data members
Data members that are references
1 // Example 18
2 // Using a member initializer to initialize a
3 // constant of a built-in data type.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 class Increment {
10
11 public:
12 Increment( int c = 0, int i = 1 ); // default constructor
13
14 void addIncrement()
15 {
16 count += increment;
17
18 } // end function addIncrement
19
20 void print() const; // prints count and increment
21
22 private:
23 int count;
24 const int increment; // const data member
25
26 }; // end class Increment
27
28 // constructor
29 Increment::Increment( int c, int i )
30 : count( c ), // initializer for non-const member
31 increment( i ) // required initializer for const member
32 {
33 // empty body
34
35 } // end Increment constructor
36
37 // print count and increment values
38 void Increment::print() const
39 {
40 cout << "count = " << count
41 << ", increment = " << increment << endl;
42
43 } // end function print
44
Declare increment as const
data member.
Member initializer list
separated from parameter list
by colon.
Member initializer syntax can
be used for non-const data
member count.
Member initializer syntax
must be used for const data
member increment.
Member initializer consists of
data member name
(increment) followed by
parentheses containing initial
value (c).
Composition: Objects as Members of
Classes
 Composition
 Class has objects of other classes as members
 Construction of objects
 Member objects constructed in order declared
 Not in order of constructor’s member initializer list
 Constructed before enclosing class objects (host objects)
1 // Example 19
2 // Date class definition.
3 // Member functions defined in date1.cpp
4 #ifndef DATE1_H
5 #define DATE1_H
6
7 class Date {
8
9 public:
10 Date( int = 1, int = 1, int = 1900 ); // default constructor
11 void print() const; // print date in month/day/year format
12 ~Date(); // provided to confirm destruction order
13
14 private:
15 int month; // 1-12 (January-December)
16 int day; // 1-31 based on month
17 int year; // any year
18
19 // utility function to test proper day for month and year
20 int checkDay( int ) const;
21
22 }; // end class Date
23
24 #endif
Note no constructor with
parameter of type Date.
Recall compiler provides
default copy constructor.
1 // EXAMPLE 20
2 // Employee class definition.
3 // Member functions defined in employee1.cpp.
4 #ifndef EMPLOYEE1_H
5 #define EMPLOYEE1_H
6
7 // include Date class definition from date1.h
8 #include "date1.h"
9
10 class Employee {
11
12 public:
13 Employee(
14 const char *, const char *, const Date &, const Date & );
15
16 void print() const;
17 ~Employee(); // provided to confirm destruction order
18
19 private:
20 char firstName[ 25 ];
21 char lastName[ 25 ];
22 const Date birthDate; // composition: member object
23 const Date hireDate; // composition: member object
24
25 }; // end class Employee
Using composition;
Employee object contains
Date objects as data
members.
13 // constructor uses member initializer list to pass initializer
14 // values to constructors of member objects birthDate and
15 // hireDate [Note: This invokes the so-called "default copy
16 // constructor" which the C++ compiler provides implicitly.]
17 Employee::Employee( const char *first, const char *last,
18 const Date &dateOfBirth, const Date &dateOfHire )
19 : birthDate( dateOfBirth ), // initialize birthDate
20 hireDate( dateOfHire ) // initialize hireDate
21 {
22 // copy first into firstName and be sure that it fits
23 int length = strlen( first );
24 length = ( length < 25 ? length : 24 );
25 strncpy( firstName, first, length );
26 firstName[ length ] = '0';
27
28 // copy last into lastName and be sure that it fits
29 length = strlen( last );
30 length = ( length < 25 ? length : 24 );
31 strncpy( lastName, last, length );
32 lastName[ length ] = '0';
33
34 // output Employee object to show when constructor is called
35 cout << "Employee object constructor: "
36 << firstName << ' ' << lastName << endl;
37
Member initializer syntax to
initialize Date data members
birthDate and
hireDate; compiler uses
default copy constructor.
Output to show timing of
constructors.
1 // Example 21
2 // Demonstrating composition--an object with member objects.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include "employee1.h" // Employee class definition
9
10 int main()
11 {
12 Date birth( 7, 24, 1949 );
13 Date hire( 3, 12, 1988 );
14 Employee manager( "Bob", "Jones", birth, hire );
15
16 cout << 'n';
17 manager.print();
18
19 cout << "nTest Date constructor with invalid values:n";
20 Date lastDayOff( 14, 35, 1994 ); // invalid month and day
21 cout << endl;
22
23 return 0;
24
25 } // end main
Create Date objects to pass
to Employee constructor.
friend Functions and friend
Classes
 friend function
 Defined outside class’s scope
 Right to access non-public members
 Declaring friends
 Function
 Precede function prototype with keyword friend
 Want to make all member functions of class ClassTwo as friends of class
ClassOne
 Place declaration of form
friend class ClassTwo;
in ClassOne definition
friend Functions and
friend Classes
 Properties of friendship
 Friendship granted, not taken
 Class B friend of class A
Class A must explicitly declare class B friend
 Not symmetric
 Class B friend of class A
 Class A not necessarily friend of class B
 Not transitive
 Class A friend of class B
 Class B friend of class C
 Class A not necessarily friend of Class C
1 // Example 22
2 // Friends can access private members of a class.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // Count class definition
9 class Count {
10 friend void setX( Count &, int ); // friend declaration
11
12 public:
13
14 // constructor
15 Count()
16 : x( 0 ) // initialize x to 0
17 {
18 // empty body
19
20 } // end Count constructor
21
Precede function prototype
with keyword friend.
22 // output x
23 void print() const
24 {
25 cout << x << endl;
26
27 } // end function print
28
29 private:
30 int x; // data member
31
32 }; // end class Count
33
34 // function setX can modify private data of Count
35 // because setX is declared as a friend of Count
36 void setX( Count &c, int val )
37 {
38 c.x = val; // legal: setX is a friend of Count
39
40 } // end function setX
41
Pass Count object since C-
style, standalone function.
Since setX friend of
Count, can access and
modify private data
member x.
42 int main()
43 {
44 Count counter; // create Count object
45
46 cout << "counter.x after instantiation: ";
47 counter.print();
48
49 setX( counter, 8 ); // set x with a friend
50
51 cout << "counter.x after call to setX friend function: ";
52 counter.print();
53
54 return 0;
55
56 } // end main
counter.x after instantiation: 0
counter.x after call to setX friend function: 8
Use friend function to
access and modify private
data member x.
Using the this Pointer
 this pointer
 Allows object to access own address
 Not part of object itself
 Implicit argument to non-static member function call
 Implicitly reference member data and functions
 Type of this pointer depends on
 Type of object
 Whether member function is const
 In non-const member function of Employee
this has type Employee * const
 Constant pointer to non-constant Employee object
 In const member function of Employee
this has type const Employee * const
 Constant pointer to constant Employee object
1 // Example 23
2 // Using the this pointer to refer to object members.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 class Test {
9
10 public:
11 Test( int = 0 ); // default constructor
12 void print() const;
13
14 private:
15 int x;
16
17 }; // end class Test
18
19 // constructor
20 Test::Test( int value )
21 : x( value ) // initialize x to value
22 {
23 // empty body
24
25 } // end Test constructor
26
27 // print x using implicit and explicit this pointers;
28 // parentheses around *this required
29 void Test::print() const
30 {
31 // implicitly use this pointer to access member x
32 cout << " x = " << x;
33
34 // explicitly use this pointer to access member x
35 cout << "n this->x = " << this->x;
36
37 // explicitly use dereferenced this pointer and
38 // the dot operator to access member x
39 cout << "n(*this).x = " << ( *this ).x << endl;
40
41 } // end function print
42
43 int main()
44 {
45 Test testObject( 12 );
46
47 testObject.print();
48
49 return 0;
50
Implicitly use this pointer;
only specify name of data
member (x).
Explicitly use this pointer
with arrow operator.
Explicitly use this pointer;
dereference this pointer
first, then use dot operator.
51 } // end main
x = 12
this->x = 12
(*this).x = 12
Using the this Pointer
 Cascaded member function calls
 Multiple functions invoked in same statement
 Function returns reference pointer to same object
{ return *this; }
 Other functions operate on that pointer
 Functions that do not return references must be called last
1 // Example 24
2 // Cascading member function calls.
3
4 // Time class definition.
5 // Member functions defined in time6.cpp.
6 #ifndef TIME6_H
7 #define TIME6_H
8
9 class Time {
10
11 public:
12 Time( int = 0, int = 0, int = 0 ); // default constructor
13
14 // set functions
15 Time &setTime( int, int, int ); // set hour, minute, second
16 Time &setHour( int ); // set hour
17 Time &setMinute( int ); // set minute
18 Time &setSecond( int ); // set second
19
20 // get functions (normally declared const)
21 int getHour() const; // return hour
22 int getMinute() const; // return minute
23 int getSecond() const; // return second
24
Set functions return reference
to Time object to enable
cascaded member function
calls.
25 // print functions (normally declared const)
26 void printUniversal() const; // print universal time
27 void printStandard() const; // print standard time
28
29 private:
30 int hour; // 0 - 23 (24-hour clock format)
31 int minute; // 0 - 59
32 int second; // 0 - 59
33
34 }; // end class Time
35
36 #endif
1 // Example 25
2 // Member-function definitions for Time class.
3 #include <iostream>
4
5 using std::cout;
6
7 #include <iomanip>
8
9 using std::setfill;
10 using std::setw;
11
12 #include "time6.h" // Time class definition
13
14 // constructor function to initialize private data;
15 // calls member function setTime to set variables;
16 // default values are 0 (see class definition)
17 Time::Time( int hr, int min, int sec )
18 {
19 setTime( hr, min, sec );
20
21 } // end Time constructor
22
23 // set values of hour, minute, and second
24 Time &Time::setTime( int h, int m, int s )
25 {
26 setHour( h );
27 setMinute( m );
28 setSecond( s );
29
30 return *this; // enables cascading
31
32 } // end function setTime
33
34 // set hour value
35 Time &Time::setHour( int h )
36 {
37 hour = ( h >= 0 && h < 24 ) ? h : 0;
38
39 return *this; // enables cascading
40
41 } // end function setHour
42
Return *this as reference to
enable cascaded member
function calls.
Return *this as reference to
enable cascaded member
function calls.
43 // set minute value
44 Time &Time::setMinute( int m )
45 {
46 minute = ( m >= 0 && m < 60 ) ? m : 0;
47
48 return *this; // enables cascading
49
50 } // end function setMinute
51
52 // set second value
53 Time &Time::setSecond( int s )
54 {
55 second = ( s >= 0 && s < 60 ) ? s : 0;
56
57 return *this; // enables cascading
58
59 } // end function setSecond
60
61 // get hour value
62 int Time::getHour() const
63 {
64 return hour;
65
66 } // end function getHour
67
Return *this as reference to
enable cascaded member
function calls.
Return *this as reference to
enable cascaded member
function calls.
68 // get minute value
69 int Time::getMinute() const
70 {
71 return minute;
72
73 } // end function getMinute
74
75 // get second value
76 int Time::getSecond() const
77 {
78 return second;
79
80 } // end function getSecond
81
82 // print Time in universal format
83 void Time::printUniversal() const
84 {
85 cout << setfill( '0' ) << setw( 2 ) << hour << ":"
86 << setw( 2 ) << minute << ":"
87 << setw( 2 ) << second;
88
89 } // end function printUniversal
90
91 // print Time in standard format
92 void Time::printStandard() const
93 {
94 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
95 << ":" << setfill( '0' ) << setw( 2 ) << minute
96 << ":" << setw( 2 ) << second
97 << ( hour < 12 ? " AM" : " PM" );
98
99 } // end function printStandard
1 // Example 26
2 // Cascading member function calls with the this pointer.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include "time6.h" // Time class definition
9
10 int main()
11 {
12 Time t;
13
14 // cascaded function calls
15 t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );
16
17 // output time in universal and standard formats
18 cout << "Universal time: ";
19 t.printUniversal();
20
21 cout << "nStandard time: ";
22 t.printStandard();
23
24 cout << "nnNew standard time: ";
25
Cascade member function
calls; recall dot operator
associates from left to right.
26 // cascaded function calls
27 t.setTime( 20, 20, 20 ).printStandard();
28
29 cout << endl;
30
31 return 0;
32
33 } // end main
Universal time: 18:30:22
Standard time: 6:30:22 PM
New standard time: 8:20:20 PM
Function call to
printStandard must
appear last;
printStandard does not
return reference to t.
Dynamic Memory Management with
Operators new and delete
Dynamic memory management
Control allocation and deallocation of memory
Operators new and delete
 Include standard header <new>
new
Time *timePtr;
timePtr = new Time;
Creates object of proper size for type Time
 Error if no space in memory for object
Calls default constructor for object
Returns pointer of specified type
Providing initializers
double *ptr = new double( 3.14159 );
Time *timePtr = new Time( 12, 0, 0 );
Allocating arrays
int *gradesArray = new int[ 10 ];
Dynamic Memory Management with
Operators new and delete
 delete
 Destroy dynamically allocated object and free space
 Consider
delete timePtr;
 Operator delete
 Calls destructor for object
 Deallocates memory associated with object
Memory can be reused to allocate other objects
 Deallocating arrays
delete [] gradesArray;
Deallocates array to which gradesArray points
 If pointer to array of objects
 First calls destructor for each object in array
 Then deallocates memory
static Class Members
 static class variable
 “Class-wide” data
 Property of class, not specific object of class
 Efficient when single copy of data is enough
 Only the static variable has to be updated
 May seem like global variables, but have class scope
 Only accessible to objects of same class
 Initialized exactly once at file scope
 Exist even if no objects of class exist
 Can be public, private or protected
static Class Members
Accessing static class variables
 Accessible through any object of class
 public static variables
 Can also be accessed using binary scope resolution operator(::)
Employee::count
 private static variables
 When no class member objects exist: Can only be accessed via
public static member function
Employee::getCount()
static member functions
 Cannot access non-static data or functions
 No this pointer for static functions
 static data members and static member functions exist
independent of objects
1 // Example 26
2 // Employee class definition.
3 #ifndef EMPLOYEE2_H
4 #define EMPLOYEE2_H
5
6 class Employee {
7
8 public:
9 Employee( const char *, const char * ); // constructor
10 ~Employee(); // destructor
11 const char *getFirstName() const; // return first name
12 const char *getLastName() const; // return last name
13
14 // static member function
15 static int getCount(); // return # objects instantiated
16
17 private:
18 char *firstName;
19 char *lastName;
20
21 // static data member
22 static int count; // number of objects instantiated
23
24 }; // end class Employee
25
static member function
can only access static data
members and member
functions.
static data member is
class-wide data.
1 // Example 27
2 // Member-function definitions for class Employee.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <new> // C++ standard new operator
9 #include <cstring> // strcpy and strlen prototypes
10
11 #include "employee2.h" // Employee class definition
12
13 // define and initialize static data member
14 int Employee::count = 0;
15
16 // define static member function that returns number of
17 // Employee objects instantiated
18 int Employee::getCount()
19 {
20 return count;
21
22 } // end static function getCount
Initialize static data
member exactly once at file
scope.
static member function
accesses static data
member count.
23
24 // constructor dynamically allocates space for
25 // first and last name and uses strcpy to copy
26 // first and last names into the object
27 Employee::Employee( const char *first, const char *last )
28 {
29 firstName = new char[ strlen( first ) + 1 ];
30 strcpy( firstName, first );
31
32 lastName = new char[ strlen( last ) + 1 ];
33 strcpy( lastName, last );
34
35 ++count; // increment static count of employees
36
37 cout << "Employee constructor for " << firstName
38 << ' ' << lastName << " called." << endl;
39
40 } // end Employee constructor
41
42 // destructor deallocates dynamically allocated memory
43 Employee::~Employee()
44 {
45 cout << "~Employee() called for " << firstName
46 << ' ' << lastName << endl;
47
new operator dynamically
allocates space.
Use static data member to
store total count of
employees.
48 delete [] firstName; // recapture memory
49 delete [] lastName; // recapture memory
50
51 --count; // decrement static count of employees
52
53 } // end destructor ~Employee
54
55 // return first name of employee
56 const char *Employee::getFirstName() const
57 {
58 // const before return type prevents client from modifying
59 // private data; client should copy returned string before
60 // destructor deletes storage to prevent undefined pointer
61 return firstName;
62
63 } // end function getFirstName
64
65 // return last name of employee
66 const char *Employee::getLastName() const
67 {
68 // const before return type prevents client from modifying
69 // private data; client should copy returned string before
70 // destructor deletes storage to prevent undefined pointer
71 return lastName;
72
73 } // end function getLastName
Operator delete deallocates
memory.
Use static data member to
store total count of
employees.
Data Abstraction and
Information Hiding
 Information hiding
 Classes hide implementation details from clients
 Example: stack data structure
 Data elements added (pushed) onto top
 Data elements removed (popped) from top
 Last-in, first-out (LIFO) data structure
 Client only wants LIFO data structure
Does not care how stack implemented
 Data abstraction
 Describe functionality of class independent of implementation
Data Abstraction and
Information Hiding
 Abstract data types (ADTs)
 Approximations/models of real-world concepts and behaviors
 int, float are models for a numbers
 Data representation
 Operations allowed on those data
 C++ extensible
 Standard data types cannot be changed, but new data types can be created
Proxy Classes
 Proxy class
 Hide implementation details of another class
 Knows only public interface of class being hidden
 Enables clients to use class’s services without giving access to class’s
implementation
 Forward class declaration
 Used when class definition only uses pointer to another class
 Prevents need for including header file
 Declares class before referencing
 Format:
class ClassToLoad;
1 // Example 28
2 // Header file for class Implementation
3
4 class Implementation {
5
6 public:
7
8 // constructor
9 Implementation( int v )
10 : value( v ) // initialize value with v
11 {
12 // empty body
13
14 } // end Implementation constructor
15
16 // set value to v
17 void setValue( int v )
18 {
19 value = v; // should validate v
20
21 } // end function setValue
22
public member function.
23
// return value
24 int getValue() const
25 {
26 return value;
27
28 } // end function getValue
29
30 private:
31 int value;
32
33 }; // end class Implementation
1 // Example 29
2 // Header file for interface.cpp
3
4 class Implementation; // forward class declaration
5
6 class Interface {
7
8 public:
9 Interface( int );
10 void setValue( int ); // same public interface as
11 int getValue() const; // class Implementation
12 ~Interface();
13
14 private:
15
16 // requires previous forward declaration (line 4)
17 Implementation *ptr;
18
19 }; // end class Interface
Provide same public
interface as class
Implementation; recall
setValue and getValue
only public member
functions.
Pointer to
Implementation object
requires forward class
declaration.
1 // Example 30
2 // Definition of class Interface
3 #include "interface.h" // Interface class definition
4 #include "implementation.h" // Implementation class definition
5
6 // constructor
7 Interface::Interface( int v )
8 : ptr ( new Implementation( v ) ) // initialize ptr
9 {
10 // empty body
11
12 } // end Interface constructor
13
14 // call Implementation's setValue function
15 void Interface::setValue( int v )
16 {
17 ptr->setValue( v );
18
19 } // end function setValue
20
Proxy class Interface
includes header file for class
Implementation.
Maintain pointer to
underlying
Implementation object.
Invoke corresponding
function on underlying
Implementation object.
21 // call Implementation's getValue function
22 int Interface::getValue() const
23 {
24 return ptr->getValue();
25
26 } // end function getValue
27
28 // destructor
29 Interface::~Interface()
30 {
31 delete ptr;
32
33 } // end destructor ~Interface
Invoke corresponding
function on underlying
Implementation object.
Deallocate underlying
Implementation object.
1 // Example 30
2 // Hiding a class’s private data with a proxy class.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include "interface.h" // Interface class definition
9
10 int main()
11 {
12 Interface i( 5 );
13
14 cout << "Interface contains: " << i.getValue()
15 << " before setValue" << endl;
16
17 i.setValue( 10 );
18
19 cout << "Interface contains: " << i.getValue()
20 << " after setValue" << endl;
21
22 return 0;
23
24 } // end main
Interface contains: 5 before setValue
Interface contains: 10 after setValue
Only include proxy class
header file.
Create object of proxy class
Interface; note no
mention of
Implementation class.
Invoke member functions via
proxy class object.
Fundamentals of Operator
Overloading
 Use operators with objects (operator overloading)
 Clearer than function calls for certain classes
 Operator sensitive to context
 Types
 Built in (int, char) or user-defined
 Can use existing operators with user-defined types
 Cannot create new operators
 Overloading operators
 Create a function for the class
 Name function operator followed by symbol
 Operator+ for the addition operator +
Fundamentals of Operator
Overloading
 Using operators on a class object
 It must be overloaded for that class
 Exceptions:
 Assignment operator, =
May be used without explicit overloading
Memberwise assignment between objects
 Address operator, &
May be used on any class without overloading
Returns address of object
 Both can be overloaded
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course
Complete C++ programming Language Course

More Related Content

What's hot (20)

Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
C functions
C functionsC functions
C functions
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
C++ language basic
C++ language basicC++ language basic
C++ language basic
 
Inline function
Inline functionInline function
Inline function
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
Loops c++
Loops c++Loops c++
Loops c++
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
C vs c++
C vs c++C vs c++
C vs c++
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++
 
Switch case in C++
Switch case in C++Switch case in C++
Switch case in C++
 

Viewers also liked

Viewers also liked (6)

C++ language
C++ languageC++ language
C++ language
 
Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
presentation on C++ basics by prince kumar kushwaha
presentation on C++ basics by prince kumar kushwahapresentation on C++ basics by prince kumar kushwaha
presentation on C++ basics by prince kumar kushwaha
 
20130110 prs presentation ncim c++ 11
20130110 prs presentation ncim c++ 1120130110 prs presentation ncim c++ 11
20130110 prs presentation ncim c++ 11
 
Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 

Similar to Complete C++ programming Language Course

Similar to Complete C++ programming Language Course (20)

Oop lec 1
Oop lec 1Oop lec 1
Oop lec 1
 
C Introduction
C IntroductionC Introduction
C Introduction
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
 
C Intro.ppt
C Intro.pptC Intro.ppt
C Intro.ppt
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
intro to c
intro to cintro to c
intro to c
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Programming in C
Programming in CProgramming in C
Programming in C
 
C notes for exam preparation
C notes for exam preparationC notes for exam preparation
C notes for exam preparation
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
4. programing 101
4. programing 1014. programing 101
4. programing 101
 
Switch case looping
Switch case loopingSwitch case looping
Switch case looping
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 

More from Vivek chan

Deceptive Marketing.pdf
Deceptive Marketing.pdfDeceptive Marketing.pdf
Deceptive Marketing.pdfVivek chan
 
brain controled wheel chair.pdf
brain controled wheel chair.pdfbrain controled wheel chair.pdf
brain controled wheel chair.pdfVivek chan
 
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)Vivek chan
 
Manav dharma shashtra tatha shashan paddati munshiram jigyasu
Manav dharma shashtra tatha shashan paddati   munshiram jigyasuManav dharma shashtra tatha shashan paddati   munshiram jigyasu
Manav dharma shashtra tatha shashan paddati munshiram jigyasuVivek chan
 
Self driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking driversSelf driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking driversVivek chan
 
EEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using ThoughtsEEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using ThoughtsVivek chan
 
Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek chan
 
Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek chan
 
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)Vivek chan
 
Net framework session01
Net framework session01Net framework session01
Net framework session01Vivek chan
 
Net framework session03
Net framework session03Net framework session03
Net framework session03Vivek chan
 
Net framework session02
Net framework session02Net framework session02
Net framework session02Vivek chan
 
04 intel v_tune_session_05
04 intel v_tune_session_0504 intel v_tune_session_05
04 intel v_tune_session_05Vivek chan
 
03 intel v_tune_session_04
03 intel v_tune_session_0403 intel v_tune_session_04
03 intel v_tune_session_04Vivek chan
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02Vivek chan
 
01 intel v_tune_session_01
01 intel v_tune_session_0101 intel v_tune_session_01
01 intel v_tune_session_01Vivek chan
 
09 intel v_tune_session_13
09 intel v_tune_session_1309 intel v_tune_session_13
09 intel v_tune_session_13Vivek chan
 
07 intel v_tune_session_10
07 intel v_tune_session_1007 intel v_tune_session_10
07 intel v_tune_session_10Vivek chan
 
02 asp.net session02
02 asp.net session0202 asp.net session02
02 asp.net session02Vivek chan
 
01 asp.net session01
01 asp.net session0101 asp.net session01
01 asp.net session01Vivek chan
 

More from Vivek chan (20)

Deceptive Marketing.pdf
Deceptive Marketing.pdfDeceptive Marketing.pdf
Deceptive Marketing.pdf
 
brain controled wheel chair.pdf
brain controled wheel chair.pdfbrain controled wheel chair.pdf
brain controled wheel chair.pdf
 
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
 
Manav dharma shashtra tatha shashan paddati munshiram jigyasu
Manav dharma shashtra tatha shashan paddati   munshiram jigyasuManav dharma shashtra tatha shashan paddati   munshiram jigyasu
Manav dharma shashtra tatha shashan paddati munshiram jigyasu
 
Self driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking driversSelf driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking drivers
 
EEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using ThoughtsEEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using Thoughts
 
Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant
 
Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant
 
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
 
Net framework session01
Net framework session01Net framework session01
Net framework session01
 
Net framework session03
Net framework session03Net framework session03
Net framework session03
 
Net framework session02
Net framework session02Net framework session02
Net framework session02
 
04 intel v_tune_session_05
04 intel v_tune_session_0504 intel v_tune_session_05
04 intel v_tune_session_05
 
03 intel v_tune_session_04
03 intel v_tune_session_0403 intel v_tune_session_04
03 intel v_tune_session_04
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02
 
01 intel v_tune_session_01
01 intel v_tune_session_0101 intel v_tune_session_01
01 intel v_tune_session_01
 
09 intel v_tune_session_13
09 intel v_tune_session_1309 intel v_tune_session_13
09 intel v_tune_session_13
 
07 intel v_tune_session_10
07 intel v_tune_session_1007 intel v_tune_session_10
07 intel v_tune_session_10
 
02 asp.net session02
02 asp.net session0202 asp.net session02
02 asp.net session02
 
01 asp.net session01
01 asp.net session0101 asp.net session01
01 asp.net session01
 

Recently uploaded

Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPCeline George
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...HetalPathak10
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...Nguyen Thanh Tu Collection
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Osopher
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 

Recently uploaded (20)

Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERP
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
Chi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical VariableChi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical Variable
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 

Complete C++ programming Language Course

  • 2. Topics for C++ Language 1.Introduction to C++ language 2.Structured/OO Programming 3.Memory Concepts 4.Arithmetic 5.Control Structure 6.Functions 7.Arrays 8.Pointers 9.Structures 10.Inheritance 11.Polymorphism 12.Multiple Inheritance 13.Templetes 14.Stacks/Queue 15.Exception Handling 16.Preprocessing 17.Unified Modeling Language
  • 3. Introduction to C++ language Course Description  An introduction to the development of programs using C++.  Emphasis is given to the development of program modules that can function independently.  Object-oriented design  The theory of data structures and programming language design is continued. Course Information
  • 4. Computer Languages  Machine language  Generally consist of strings of numbers - Ultimately 0s and 1s - Machine-dependent  Example: +1300042774 +1400593419  Assembly language  English-like abbreviations for elementary operations  Incomprehensible to computers - Convert to machine language  Example: LOAD BASEPAY ADD OVERPAY STORE GROSSPAY  High-level languages  Similar to everyday English, use common mathematical notations  Compiler/Interpreter  Example: grossPay = basePay + overTimePay
  • 5. History of C and C++  History of C  Evolved from two other programming languages  BCPL and B: “Typeless” languages  Dennis Ritchie (Bell Lab): Added typing, other features  1989: ANSI standard/ ANSI/ISO 9899: 1990  History of C++  Early 1980s: Bjarne Stroustrup (Bell Lab)  Provides capabilities for object-oriented programming  Objects: reusable software components  Object-oriented programs  Building block approach” to creating programs  C++ programs are built from pieces called classes and functions  C++ standard library: Rich collections of existing classes and functions
  • 6. Structured/OO Programming  Structured programming (1960s)  Disciplined approach to writing programs  Clear, easy to test and debug, and easy to modify  E.g.Pascal:1971: Niklaus Wirth  OOP  “Software reuse”  “Modularity”  “Extensible”  More understandable, better organized and easier to maintain than procedural programming
  • 7. Basics of a Typical C++ Environment  C++ systems  Program-development environment  Language  C++ Standard Library  C++ program names extensions  .cpp  .cxx  .cc  .C
  • 8. Basics of a Typical C++ Environment Phases of C++ Programs: 1. Edit 2. Preprocess 3. Compile 4. Link 5. Load 6. Execute Loader Primary Memory Program is created in the editor and stored on disk. Preprocessor program processes the code. Loader puts program in memory. CPU takes each instruction and executes it, possibly storing new data values as the program executes. Compiler Compiler creates object code and stores it on disk. Linker links the object code with the libraries, creates an executable file and stores it on disk Editor Preprocessor Linker CPU Primary Memory . . . . . . . . . . . . Disk Disk Disk Disk Disk
  • 9. Basics of a Typical C++ Environment  Common Input/output functions  cin  Standard input stream  Normally keyboard  cout  Standard output stream  Normally computer screen  cerr  Standard error stream  Display error messages  Comments: C’s comment /* .. */ OR Begin with // or  Preprocessor directives: Begin with #  Processed before compiling
  • 10. A Simple Program: Printing a Line of Text  Standard output stream object  std::cout  “Connected” to screen  <<  Stream insertion operator  Value to right (right operand) inserted into output stream  Namespace  std:: specifies that entity belongs to “namespace” std  std:: removed through use of using statements  Escape characters:  Indicates “special” character output
  • 11. 1 // Example 1 2 // A first program in C++. 3 #include <iostream> 4 5 // function main begins program execution 6 int main() 7 { 8 std::cout << "Welcome to C++!n"; 9 10 return 0; // indicate that program ended successfully 11 12 } // end function main Welcome to C++!
  • 12. A Simple Program: Printing a Line of Text Escape Sequence Description n Newline. Position the screen cursor to the beginning of the next line. t Horizontal tab. Move the screen cursor to the next tab stop. r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. a Alert. Sound the system bell. Backslash. Used to print a backslash character. " Double quote. Used to print a double quote character.
  • 13. Memory Concepts  Variable names  Correspond to actual locations in computer's memory  Every variable has name, type, size and value  When new value placed into variable, overwrites previous value  std::cin >> integer1;  Assume user entered 45  std::cin >> integer2;  Assume user entered 72  sum = integer1 + integer2; integer1 45 integer1 45 integer2 72 integer1 45 integer2 72 sum 117
  • 14. Arithmetic  Arithmetic calculations  * : Multiplication  / : Division  Integer division truncates remainder 7 / 5 evaluates to 1  % : Modulus operator returns remainder 7 % 5 evaluates to 2 Operator(s) Operation(s) Order of evaluation (precedence) () Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right. *, /, or % Multiplication Division Modulus Evaluated second. If there are several, they re evaluated left to right. + or - Addition Subtraction Evaluated last. If there are several, they are evaluated left to right.
  • 15. Decision Making: Equality and Relational Operators  if structure  Make decision based on truth or falsity of condition  If condition met, body executed  Else, body not executed  Equality and relational operators  Equality operators  Same level of precedence  Relational operators  Same level of precedence  Associate left to right
  • 16. Decision Making: Equality and Relational Operators Standard algebraic equality operator or relational operator C++ equality or relational operator Example of C++ condition Meaning of C++ condition Relational operators > > x > y x is greater than y < < x < y x is less than y  >= x >= y x is greater than or equal to y  <= x <= y x is less than or equal to y Equality operators = == x == y x is equal to y  != x != y x is not equal to y
  • 17. Algorithms /pseudocode  Computing problems  Solved by executing a series of actions in a specific order  Algorithm: a procedure determining  Actions to be executed  Order to be executed  Example: recipe  Program control  Specifies the order in which statements are executed  Pseudocode  Artificial, informal language used to develop algorithms  Similar to everyday English
  • 18. Control Structures  Sequential execution  Statements executed in order  Transfer of control  Next statement executed not next one in sequence  Structured programming – “goto”-less programming  3 control structures to build any program  Sequence structure  Programs executed sequentially by default  Selection structures  if, if/else, switch  Repetition structures  while, do/while, for
  • 19. Keywords  C++ keywords  Cannot be used as identifiers or variable names C++ Keywords Keywords common to the C and C++ programming languages auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while C++ only keywords asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t
  • 20. Control Structures  Flowchart  Graphical representation of an algorithm  Special-purpose symbols connected by arrows (flowlines)  Rectangle symbol (action symbol)  Any type of action  Oval symbol  Beginning or end of a program, or a section of code (circles) Exercise: Find greater of three numbers
  • 21. if/else Selection Structure  Ternary conditional operator (?:)  Three arguments (condition, value if true, value if false)  Code could be written: cout << ( grade >= 60 ? “Passed” : “Failed” ); truefalse print “Failed” print “Passed” grade >= 60 Condition Value if true Value if false
  • 22. while Repetition Structure  Repetition structure  Counter-controlled  While/do while loop: repeated until condition becomes false  For: loop repeated until counter reaches certain value Flowchart representation?  Sentinel value  Indicates “end of data entry”  Sentinel chosen so it cannot be confused with regular input  Example int product = 2; while ( product <= 1000 ) { product = 2 * product; cout << product; } Flowchart representation? What is the output?
  • 23. switch Multiple-Selection Structure  switch  Test variable for multiple values  Series of case labels and optional default case switch ( variable ) { case value1: // taken if variable == value1 statements break; // necessary to exit switch case value2: case value3: // taken if variable == value2 or == value3 statements break; default: // taken if none matches statements break; }
  • 24. break and continue Statements  break statement  Immediate exit from while, for, do/while, switch  Program continues with first statement after structure  Common uses  Escape early from a loop  Skip the remainder of switch
  • 25. Logical Operators  Used as conditions in loops, if statements  && (logical AND)  true if both conditions are true if ( gender == 1 && age >= 65 ) ++seniorFemales;  || (logical OR)  true if either of condition is true if ( semesterAverage >= 90 || finalExam >= 90 ) cout << "Student grade is A" << endl;
  • 26. Logical Operators  ! (logical NOT, logical negation)  Returns true when its condition is false, & vice versa if ( !( grade == sentinelValue ) ) cout << "The next grade is " << grade << endl; Alternative: if ( grade != sentinelValue ) cout << "The next grade is " << grade << endl;
  • 27. Confusing Equality (==) and Assignment (=) Operators  Common error  Does not typically cause syntax errors  Aspects of problem  Expressions that have a value can be used for decision  Zero = false, nonzero = true  Assignment statements produce a value (the value to be assigned) if == was replaced with = if ( payCode = 4 ) cout << "You get a bonus!" << endl; What happens?
  • 28. Confusing Equality (==) and Assignment (=) Operators  Lvalues  Expressions that can appear on left side of equation  Can be changed x = 4;  Rvalues  Only appear on right side of equation  Constants, such as numbers (i.e. cannot write 4 = x;)  Lvalues can be used as rvalues, but not vice versa
  • 29. Structured-Programming Summary  Structured programming  Programs easier to understand, test, debug and modify  Rules for structured programming  Only use single-entry/single-exit control structures  Rules 1) Begin with the “simplest flowchart” 2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence 3) Any rectangle (action) can be replaced by any control structure (sequence, if, if/else, switch, while, do/while or for) 4) Rules 2 and 3 can be applied in any order and multiple times
  • 30. Structured-Programming Summary Representation of Rule 3 (replacing any rectangle with a control structure) Rule 3 Rule 3Rule 3
  • 31. Program Components in C++  Modules: functions and classes  Programs use new and “prepackaged” modules  New: programmer-defined functions, classes  Prepackaged: from the standard library  Functions invoked by function call  Function name and information (arguments) it needs  Function definitions  Only written once  Hidden from other functions
  • 32. Functions  Functions  Modularize a program  Software reusability  Call function multiple times  Local variables  Known only in the function in which they are defined  All variables declared in function definitions are local variables  Parameters  Local variables passed to function when called  Provide outside information
  • 33. Math Library Functions Perform common mathematical calculations Include the header file <cmath> Functions called by writing functionName (argument); or functionName (argument1, argument2, …); Example cout << sqrt( 900.0 ); All functions in math library return a double Function arguments can be Constants: sqrt( 4 ); Variables: sqrt( x ); Expressions:  sqrt( sqrt( x ) ) ;  sqrt( 3 - 6x ); Other functions  ceil(x), floor(x), log10(x), etc.
  • 34. Function Definitions Function prototype int square( int ); Calling/invoking a function square(x); Format for function definition return-value-type function-name( parameter-list ) { declarations and statements } Prototype must match function definition Function prototype double maximum( double, double, double ); Definition double maximum( double x, double y, double z ) { … }
  • 35. Function Definitions  Example function int square( int y ) { return y * y; }  return keyword  Returns data, and control goes to function’s caller  If no data to return, use return;  Function ends when reaches right brace  Control goes to caller  Functions cannot be defined inside other functions
  • 36. Function Prototypes  Function signature  Part of prototype with name and parameters  double maximum( double, double, double );  Argument Coercion  Force arguments to be of proper type  Converting int (4) to double (4.0) cout << sqrt(4)  Conversion rules  Arguments usually converted automatically  Changing from double to int can truncate data 3.4 to 3  Mixed type goes to highest type (promotion) Function signature
  • 37. Function Prototypes Data types long double double float unsigned long int (synonymous with unsigned long) long int (synonymous with long) unsigned int (synonymous with unsigned) int unsigned short int (synonymous with unsigned short) short int (synonymous with short) unsigned char char bool (false becomes 0, true becomes 1) Fig. 3.5 Promotion hierarc hy for built-in data types.
  • 38. Header Files  Header files contain  Function prototypes  Definitions of data types and constants  Header files ending with .h  Programmer-defined header files #include “myheader.h”  Library header files #include <cmath>
  • 39. Enumeration: enum  Enumeration  Set of integers with identifiers enum typeName {constant1, constant2…};  Constants start at 0 (default), incremented by 1  Constants need unique names  Cannot assign integer to enumeration variable  Must use a previously defined enumeration type  Example enum Status {CONTINUE, WON, LOST}; Status enumVar; enumVar = WON; // cannot do enumVar = 1
  • 40. Storage Classes  Variables have attributes  Have seen name, type, size, value  Storage class  How long variable exists in memory  Scope  Where variable can be referenced in program  Linkage  For multiple-file program which files can use it
  • 41. Storage Classes  Automatic storage class  Variable created when program enters its block  Variable destroyed when program leaves block  Only local variables of functions can be automatic  Automatic by default  keyword auto explicitly declares automatic  register keyword  Hint to place variable in high-speed register  Good for often-used items (loop counters)  Often unnecessary, compiler optimizes  Specify either register or auto, not both  register int counter = 1;
  • 42. Storage Classes  Static storage class  Variables exist for entire program  For functions, name exists for entire program  May not be accessible, scope rules still apply  auto and register keyword  local variables in function  register variables are kept in CPU registers  static keyword  Local variables in function  Keeps value between function calls  Only known in own function  extern keyword  Default for global variables/functions  Globals: defined outside of a function block  Known in any function that comes after it
  • 43. Scope Rules  Scope  Portion of program where identifier can be used  File scope  Defined outside a function, known in all functions  Global variables, function definitions and prototypes  Function scope  Can only be referenced inside defining function  Only labels, e.g., identifiers with a colon (case:)
  • 44. Scope Rules  Block scope  Begins at declaration, ends at right brace }  Can only be referenced in this range  Local variables, function parameters  Local static variables still have block scope  Storage class separate from scope  Function-prototype scope  Parameter list of prototype  Names in prototype optional  Compiler ignores  In a single prototype, name can be used once
  • 45. 1 // Example 2 2 // A scoping example. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 void useLocal( void ); // function prototype 9 void useStaticLocal( void ); // function prototype 10 void useGlobal( void ); // function prototype 11 12 int x = 1; // global variable 13 14 int main() 15 { 16 int x = 5; // local variable to main 17 18 cout << "local x in main's outer scope is " << x << endl; 19 20 { // start new scope 21 22 int x = 7; 23 24 cout << "local x in main's inner scope is " << x << endl; 25 26 } // end new scope Local/global? Scope? Local/global? Scope? Local/global? Scope?
  • 46. 43 // useLocal reinitializes local variable x during each call 44 void useLocal( void ) 45 { 46 int x = 25; // initialized each time useLocal is called 47 48 cout << endl << "local x is " << x 49 << " on entering useLocal" << endl; 50 ++x; 51 cout << "local x is " << x 52 << " on exiting useLocal" << endl; 53 54 } // end function useLocal 55 Local/global? Scope?
  • 47. 56 // useStaticLocal initializes static local variable x only the 57 // first time the function is called; value of x is saved 58 // between calls to this function 59 void useStaticLocal( void ) 60 { 61 // initialized only first time useStaticLocal is called 62 static int x = 50; 63 64 cout << endl << "local static x is " << x 65 << " on entering useStaticLocal" << endl; 66 ++x; 67 cout << "local static x is " << x 68 << " on exiting useStaticLocal" << endl; 69 70 } // end function useStaticLocal 71 Local/global? Scope?
  • 48. Recursion  Recursive functions  Functions that call themselves  Can only solve a base case  If not base case  Break problem into smaller problem(s)  Launch new copy of function to work on the smaller problem (recursive call/recursive step)  Slowly converges towards base case  Function makes call to itself inside the return statement  Eventually base case gets solved  Answer works way back up, solves entire problem
  • 49. 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)
  • 50. Example Using Recursion: Fibonacci Series  Fibonacci series: 0, 1, 1, 2, 3, 5, 8...  Each number sum of two previous ones  Example of a recursive formula:  fib(n) = fib(n-1) + fib(n-2)  C++ code for Fibonacci function long fibonacci( long n ) { if ???? // base case return ???; else ??? }
  • 51. Example Using Recursion: Fibonacci Series  Order of operations  return fibonacci( n - 1 ) + fibonacci( n - 2 );  Recursive function calls  Each level of recursion doubles the number of function calls  30th number = 2^30 ~ 4 billion function calls  Exponential complexity f( 3 ) f( 1 )f( 2 ) f( 1 ) f( 0 ) return 1 return 1 return 0 return + +return
  • 52. Recursion vs. Iteration  Repetition  Iteration: explicit loop  Recursion: repeated function calls  Termination  Iteration: loop condition fails  Recursion: base case recognized  Both can have infinite loops  Balance between performance (iteration) and good software engineering (recursion)
  • 53. Inline Functions  Inline functions  Keyword inline before function  Asks the compiler to copy code into program instead of making function call  Reduce function-call overhead  Compiler can ignore inline  Good for small, often-used functions  Example inline double cube( const double s ) { return s * s * s; }  const tells compiler that function does not modify s
  • 54. References and Reference Parameters  Call by value  Copy of data passed to function  Changes to copy do not change original  Prevent unwanted side effects  Call by reference  Function can directly access data  Changes affect original  Reference parameter  Alias for argument in function call  Passes parameter by reference  Use & after data type in prototype  void myFunction( int &data )  Read “data is a reference to an int”  Function call format the same  However, original can now be changed
  • 55. References and Reference Parameters  Pointers  Another way to pass-by-refernce  References as aliases to other variables  Refer to same variable  Can be used within a function int count = 1; // declare integer variable count int &cRef = count; // create cRef as an alias for count ++cRef; // increment count (using its alias)  References must be initialized when declared  Otherwise, compiler error  Dangling reference  Reference to undefined variable
  • 56. Default Arguments  Function call with omitted parameters  If not enough parameters, rightmost go to their defaults  Default values  Can be constants, global variables, or function calls  Set defaults in function prototype int myFunction( int x = 1, int y = 2, int z = 3 );  myFunction(3)  x = 3, y and z get defaults (rightmost)  myFunction(3, 5)  x = 3, y = 5 and z gets default
  • 57. Unitary Scope Resolution Operator  Unary scope resolution operator (::)  Access global variable if local variable has same name  Not needed if names are different  Use ::variable  y = ::x + 3;  Good to avoid using same names for locals and globals
  • 58. Function Overloading  Function overloading  Functions with same name and different parameters  Should perform similar tasks  i.e., function to square ints and function to square floats int square( int x) {return x * x;} float square(float x) { return x * x; }  Overloaded functions distinguished by signature  Based on name and parameter types (order matters)  Name mangling  Encode function identifier with no. and types of parameters  Type-safe linkage  Ensures proper overloaded function called
  • 59. Function Templates  Compact way to make overloaded functions  Generate separate function for different data types  Format  Begin with keyword template  Formal type parameters in brackets <>  Every type parameter preceded by typename or class (synonyms)  Placeholders for built-in types (i.e., int) or user-defined types  Specify arguments types, return types, declare variables  Function definition like normal, except formal types used
  • 60. Function Templates  Example template < class T > // or template< typename T > T square( T value1 ) { return value1 * value1; }  T is a formal type, used as parameter type  Above function returns variable of same type as parameter  In function call, T replaced by real type  If int, all T's become ints int x; int y = square(x);
  • 61. 1 // Example 3 2 // Using a function template. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 // definition of function template maximum 10 template < class T > // or template < typename T > 11 T maximum( T value1, T value2, T value3 ) 12 { 13 T max = value1; 14 15 if ( value2 > max ) 16 max = value2; 17 18 if ( value3 > max ) 19 max = value3; 20 21 return max; 22 23 } // end function template maximum 24 Formal type parameter T placeholder for type of data to be tested by maximum. maximum expects all parameters to be of the same type.
  • 62. 25 int main() 26 { 27 // demonstrate maximum with int values 28 int int1, int2, int3; 29 30 cout << "Input three integer values: "; 31 cin >> int1 >> int2 >> int3; 32 33 // invoke int version of maximum 34 cout << "The maximum integer value is: " 35 << maximum( int1, int2, int3 ); 36 37 // demonstrate maximum with double values 38 double double1, double2, double3; 39 40 cout << "nnInput three double values: "; 41 cin >> double1 >> double2 >> double3; 42 43 // invoke double version of maximum 44 cout << "The maximum double value is: " 45 << maximum( double1, double2, double3 ); 46 maximum called with various data types.
  • 63. 47 // demonstrate maximum with char values 48 char char1, char2, char3; 49 50 cout << "nnInput three characters: "; 51 cin >> char1 >> char2 >> char3; 52 53 // invoke char version of maximum 54 cout << "The maximum character value is: " 55 << maximum( char1, char2, char3 ) 56 << endl; 57 58 return 0; // indicates successful termination 59 60 } // end main Input three integer values: 1 2 3 The maximum integer value is: 3 Input three double values: 3.3 2.2 1.1 The maximum double value is: 3.3 Input three characters: A C B The maximum character value is: C
  • 64. Arrays  Array  Consecutive group of memory locations  Same name and type (int, char, etc.)  To refer to an element  Specify array name and position number (index)  Format: arrayname[ position number ]  First element at position 0  N-element array c c[ 0 ], c[ 1 ] … c[ n - 1 ]  Nth element as position N-1
  • 65. Declaring Arrays  When declaring arrays, specify  Name  Type of array  Any data type  Number of elements  type arrayName[ arraySize ]; int c[ 10 ]; // array of 10 integers float d[ 3284 ]; // array of 3284 floats  Declaring multiple arrays of same type  Use comma separated list, like regular variables int b[ 100 ], x[ 27 ];
  • 66. Examples Using Arrays  Initializing arrays  For loop  Set each element  Initializer list  Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 };  If not enough initializers, rightmost elements 0  If too many, syntax error  To set every element to 0 int n[ 5 ] = { 0 };  If array size omitted, initializers determine size int n[] = { 1, 2, 3, 4, 5 };  5 initializers, therefore 5 element array  static int array[3]; ??
  • 67. Examples Using Arrays  Strings  Arrays of characters  All strings end with null ('0')  Examples  char string1[] = "hello"; Null character implicitly added string1 has 6 elements  char string1[] = { 'h', 'e', 'l', 'l', 'o', '0’ };  Subscripting is the same String1[ 0 ] is 'h' string1[ 2 ] is 'l'
  • 68. Examples Using Arrays  Input from keyboard char string2[ 10 ]; cin >> string2;  Puts user input in string  Stops at first whitespace character  Adds null character  If too much text entered, data written beyond array  We want to avoid this  Printing strings  cout << string2 << endl;  Does not work for other array types  Characters printed until null found
  • 69. Passing Arrays to Functions  Specify name without brackets  To pass array myArray to myFunction int myArray[ 24 ]; myFunction( myArray, 24 );  Array size usually passed, but not required  Useful to iterate over all elements  Arrays passed-by-reference  Functions can modify original array data  Value of name of array is address of first element  Function knows where the array is stored  Can change original memory locations
  • 70. Passing Arrays to Functions  Functions taking arrays  Function prototype  void modifyArray( int b[], int arraySize );  void modifyArray( int [], int ); Names optional in prototype  Both take an integer array and a single integer  No need for array size between brackets  Ignored by compiler  If declare array parameter as const  Cannot be modified (compiler error)  void doNotModify( const int [] );
  • 71. Sorting Arrays  Example:  Go left to right, and exchange elements as necessary  One pass for each element  Original: 3 4 2 7 6  Pass 1: 3 2 4 6 7 (elements exchanged)  Pass 2: 2 3 4 6 7  Pass 3: 2 3 4 6 7 (no changes needed)  Pass 4: 2 3 4 6 7  Pass 5: 2 3 4 6 7  Small elements "bubble" to the top (like 2 in this example)
  • 72. Multiple-Subscripted Arrays Multiple subscripts a[ i ][ j ] Tables with rows and columns Specify row, then column “Array of arrays”  a[0] is an array of 4 elements  a[0][0] is the first element of that array Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript Array name Column subscript To initialize Default of 0 Initializers grouped by row in braces int b[ 2 ][ 2 ]={ { 1, 2 }, { 3, 4 } }; int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
  • 73. Pointer  Pointer variables  Contain memory addresses as values  Normally, variable contains specific value (direct reference)  Pointers contain address of variable that has specific value (indirect reference)  Indirection  Referencing value through pointer  Pointer declarations  * indicates variable is pointer int *myPtr; declares pointer to int, pointer of type int *  Multiple pointers require multiple asterisks int *myPtr1, *myPtr2; count 7 countPtr count 7 Pointer Variable Declarations and Initialization
  • 74. Pointer Operators  & (address operator)  Returns memory address of its operand  Example int y = 5; int *yPtr; yPtr = &y; yPtr y 5 yptr 500000 600000 y 600000 5 address of y is value of yptr yPtr “points to” y * - indirection/ dereferencing operator) *yPtr returns y dereferenced pointer is lvalue *yptr = 9 ??
  • 75. Calling Functions by Reference  3 ways to pass arguments to function  Pass-by-value  Pass-by-reference with reference arguments  Pass-by-reference with pointer arguments  Arguments passed to function using reference arguments  Modify original values of arguments  More than one value “returned” int Cube(int *x) { …} Function call: Cube(&a)
  • 76. Using const with Pointers const qualifier Value of variable should not be modified const used when function does not need to change a variable Principle of least privilege const pointers Always point to same memory location Default for array name Must be initialized when declared Four ways to pass pointer to function Nonconstant pointer to nonconstant data  Highest amount of access Nonconstant pointer to constant data Constant pointer to nonconstant data Constant pointer to constant data  Least amount of access
  • 77. 1 // Example 3 2 // Attempting to modify a constant pointer to 3 // non-constant data. 4 5 int main() 6 { 7 int x, y; 8 9 // ptr is a constant pointer to an integer that can 10 // be modified through ptr, but ptr always points to the 11 // same memory location. 12 int * const ptr = &x; 13 14 *ptr = 7; // allowed: *ptr is not const 15 ptr = &y; // error: ptr is const; cannot assign new address 16 17 return 0; // indicates successful termination 18 19 } // end main d:cpphtp4_examplesch05Fig05_13.cpp(15) : error C2166: l-value specifies const object ptr is constant pointer to integer.Can modify x (pointed to by ptr) since x not constant.Cannot modify ptr to point to new address since ptr is constant. Line 15 generates compiler error by attempting to assign new address to constant pointer.
  • 78. 1 // Example 4 2 // Attempting to modify a constant pointer to constant data. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int x = 5, y; 11 12 // ptr is a constant pointer to a constant integer. 13 // ptr always points to the same location; the integer 14 // at that location cannot be modified. 15 const int *const ptr = &x; 16 17 cout << *ptr << endl; 18 19 *ptr = 7; // error: *ptr is const; cannot assign new value 20 ptr = &y; // error: ptr is const; cannot assign new address 21 22 return 0; // indicates successful termination 23 24 } // end main ptr is constant pointer to integer constant. Cannot modify x (pointed to by ptr) since *ptr declared constant. Cannot modify ptr to point to new address since ptr is constant.
  • 79. Pointer Expressions and Pointer Arithmetic Pointer arithmetic  Increment/decrement pointer (++ or --)  Add/subtract an integer to/from a pointer( + or += , - or -=)  Pointers may be subtracted from each other  Pointer arithmetic meaningless unless performed on pointer to array 5 element int array on a machine using 4 byte ints  vPtr points to first element v[ 0 ], which is at location 3000 vPtr = 3000  vPtr += 2; sets vPtr to 3008 vPtr points to v[ 2 ] pointer variable vPtr v[0] v[1] v[2] v[4]v[3] 3000 3004 3008 3012 3016 location
  • 80. Pointer Expressions and Pointer Arithmetic  Subtracting pointers  Returns number of elements between two addresses vPtr2 = v[ 2 ]; vPtr = v[ 0 ]; vPtr2 - vPtr == 2  Pointer assignment  Pointer can be assigned to another pointer if both of same type  If not same type, cast operator must be used  Exception: pointer to void (type void *)  Generic pointer, represents any type  No casting needed to convert pointer to void pointer  void pointers cannot be dereferenced
  • 81. Pointer Expressions and Pointer Arithmetic  Pointer comparison  Use equality and relational operators  Comparisons meaningless unless pointers point to members of same array  Compare addresses stored in pointers  Example: could show that one pointer points to higher numbered element of array than other pointer  Common use to determine whether pointer is 0 (does not point to anything)
  • 82. Relationship Between Pointers and Arrays  Arrays and pointers closely related  Array name like constant pointer  Pointers can do array subscripting operations  Accessing array elements with pointers  Element b[ n ] can be accessed by *( bPtr + n )  Called pointer/offset notation  Addresses  &b[ 3 ] same as bPtr + 3  Array name can be treated as pointer  b[ 3 ] same as *( b + 3 )  Pointers can be subscripted (pointer/subscript notation)  bPtr[ 3 ] same as b[ 3 ]
  • 83. Arrays of Pointers  Arrays can contain pointers  Commonly used to store array of strings char *suit[ 4 ] = {"Hearts", "Diamonds", "Clubs", "Spades" };  Each element of suit points to char * (a string)  Array does not store strings, only pointers to strings  suit array has fixed size, but strings can be of any size suit[3] suit[2] suit[1] suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’0’ ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’0’ ’C’ ’l’ ’u’ ’b’ ’s’ ’0’ ’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’0’
  • 84. Function Pointers  Calling functions using pointers  Assume parameter:  bool ( *compare ) ( int, int )  Execute function with either  ( *compare ) ( int1, int2 ) Dereference pointer to function to execute OR  compare( int1, int2 ) Could be confusing  User may think compare name of actual function in program
  • 85. 1 // Example 5 2 // Multipurpose sorting program using function pointers. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include <iomanip> 10 11 using std::setw; 12 13 // prototypes 14 void bubble( int [], const int, bool (*)( int, int ) ); 15 void swap( int * const, int * const ); 16 bool ascending( int, int ); 17 bool descending( int, int ); 18 19 int main() 20 { 21 const int arraySize = 10; 22 int order; 23 int counter; 24 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 25 Parameter is pointer to function that receives two integer parameters and returns bool result.
  • 86. 26 cout << "Enter 1 to sort in ascending order,n" 27 << "Enter 2 to sort in descending order: "; 28 cin >> order; 29 cout << "nData items in original ordern"; 30 31 // output original array 32 for ( counter = 0; counter < arraySize; counter++ ) 33 cout << setw( 4 ) << a[ counter ]; 34 35 // sort array in ascending order; pass function ascending 36 // as an argument to specify ascending sorting order 37 if ( order == 1 ) { 38 bubble( a, arraySize, ascending ); 39 cout << "nData items in ascending ordern"; 40 } 41 42 // sort array in descending order; pass function descending 43 // as an agrument to specify descending sorting order 44 else { 45 bubble( a, arraySize, descending ); 46 cout << "nData items in descending ordern"; 47 } 48
  • 87. 49 // output sorted array 50 for ( counter = 0; counter < arraySize; counter++ ) 51 cout << setw( 4 ) << a[ counter ]; 52 53 cout << endl; 54 55 return 0; // indicates successful termination 56 57 } // end main 58 59 // multipurpose bubble sort; parameter compare is a pointer to 60 // the comparison function that determines sorting order 61 void bubble( int work[], const int size, 62 bool (*compare)( int, int ) ) 63 { 64 // loop to control passes 65 for ( int pass = 1; pass < size; pass++ ) 66 67 // loop to control number of comparisons per pass 68 for ( int count = 0; count < size - 1; count++ ) 69 70 // if adjacent elements are out of order, swap them 71 if ( (*compare)( work[ count ], work[ count + 1 ] ) ) 72 swap( &work[ count ], &work[ count + 1 ] ); compare is pointer to function that receives two integer parameters and returns bool result. Parentheses necessary to indicate pointer to function Call passed function compare; dereference pointer to execute function.
  • 88. 73 74 } // end function bubble 75 76 // swap values at memory locations to which 77 // element1Ptr and element2Ptr point 78 void swap( int * const element1Ptr, int * const element2Ptr ) 79 { 80 int hold = *element1Ptr; 81 *element1Ptr = *element2Ptr; 82 *element2Ptr = hold; 83 84 } // end function swap 85 86 // determine whether elements are out of order 87 // for an ascending order sort 88 bool ascending( int a, int b ) 89 { 90 return b < a; // swap if b is less than a 91 92 } // end function ascending 93
  • 89. 94 // determine whether elements are out of order 95 // for a descending order sort 96 bool descending( int a, int b ) 97 { 98 return b > a; // swap if b is greater than a 99 100 } // end function descending Enter 1 to sort in ascending order, Enter 2 to sort in descending order: 1 Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items in ascending order 2 4 6 8 10 12 37 45 68 89 Enter 1 to sort in ascending order, Enter 2 to sort in descending order: 2 Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items in descending order 89 68 45 37 12 10 8 6 4 2
  • 90. Function Pointers  Arrays of pointers to functions  Menu-driven systems  Pointers to each function stored in array of pointers to functions  All functions must have same return type and same parameter types  Menu choice  subscript into array of function pointers
  • 91. 1 // Example 6 2 // Demonstrating an array of pointers to functions. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 // function prototypes 10 void function1( int ); 11 void function2( int ); 12 void function3( int ); 13 14 int main() 15 { 16 // initialize array of 3 pointers to functions that each 17 // take an int argument and return void 18 void (*f[ 3 ])( int ) = { function1, function2, function3 }; 19 20 int choice; 21 22 cout << "Enter a number between 0 and 2, 3 to end: "; 23 cin >> choice; 24 Array initialized with names of three functions; function names are pointers.
  • 92. 25 // process user's choice 26 while ( choice >= 0 && choice < 3 ) { 27 28 // invoke function at location choice in array f 29 // and pass choice as an argument 30 (*f[ choice ])( choice ); 31 32 cout << "Enter a number between 0 and 2, 3 to end: "; 33 cin >> choice; 34 } 35 36 cout << "Program execution completed." << endl; 37 38 return 0; // indicates successful termination 39 40 } // end main 41 42 void function1( int a ) 43 { 44 cout << "You entered " << a 45 << " so function1 was callednn"; 46 47 } // end function1 48 Call chosen function by dereferencing corresponding element in array.
  • 93. 25 // process user's choice 26 while ( choice >= 0 && choice < 3 ) { 27 28 // invoke function at location choice in array f 29 // and pass choice as an argument 30 (*f[ choice ])( choice ); 31 32 cout << "Enter a number between 0 and 2, 3 to end: "; 33 cin >> choice; 34 } 35 36 cout << "Program execution completed." << endl; 37 38 return 0; // indicates successful termination 39 40 } // end main 41 42 void function1( int a ) 43 { 44 cout << "You entered " << a 45 << " so function1 was callednn"; 46 47 } // end function1 48 Call chosen function by dereferencing corresponding element in array.
  • 94. Fundamentals of Characters and Strings  Character constant  Integer value represented as character in single quotes  'z' is integer value of z  122 in ASCII  String  Series of characters treated as single unit  Can include letters, digits, special characters +, -, * ...  String literal (string constants)  Enclosed in double quotes, for example: "I like C++"  Array of characters, ends with null character '0'  String is constant pointer  Pointer to string’s first character Like arrays
  • 95. Fundamentals of Characters and Strings  String assignment  Character array  char color[] = "blue"; Creates 5 element char array color  last element is '0'  Variable of type char *  char *colorPtr = "blue"; Creates pointer colorPtr to letter b in string “blue”  “blue” somewhere in memory  Alternative for character array  char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘0’ };
  • 96. Fundamentals of Characters and Strings  Reading strings  Assign input to character array word[ 20 ] cin >> word  Reads characters until whitespace or EOF  String could exceed array size cin >> setw( 20 ) >> word;  Reads 19 characters (space reserved for '0')
  • 97. Fundamentals of Characters and Strings  cin.getline  Read line of text  cin.getline( array, size, delimiter );  Copies input into specified array until either  One less than size is reached  delimiter character is input  Example char sentence[ 80 ]; cin.getline( sentence, 80, 'n' );
  • 98. String Manipulation Functions of the String- handling Library  String handling library <cstring> provides functions to  Manipulate string data  Compare strings  Search strings for characters and other strings  Tokenize strings (separate strings into logical pieces)
  • 99. String Manipulation Functions of the String- handling Library char *strcpy( char *s1, const char *s2 ); Copies the string s2 into the character array s1. The value of s1 is returned. char *strncpy( char *s1, const char *s2, size_t n ); Copies at most n characters of the string s2 into the character array s1. The value of s1 is returned. char *strcat( char *s1, const char *s2 ); Appends the string s2 to the string s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned. char *strncat( char *s1, const char *s2, size_t n ); Appends at most n characters of string s2 to string s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned. int strcmp( const char *s1, const char *s2 ); Compares the string s1 with the string s2. The function returns a value of zero, less than zero or greater than zero if s1 is equal to, less than or greater than s2, respectively.
  • 100. String Manipulation Functions of the String-handling Library int strncmp( const char *s1, const char *s2, size_t n ); Compares up to n characters of the string s1 with the string s2. The function returns zero, less than zero or greater than zero if s1 is equal to, less than or greater than s2, respectively. char *strtok( char *s1, const char *s2 ); A sequence of calls to strtok breaks string s1 into “tokens”—logical pieces such as words in a line of text— delimited by characters contained in string s2. The first call contains s1 as the first argument, and subsequent calls to continue tokenizing the same string contain NULL as the first argument. A pointer to the current token is returned by each call. If there are no more tokens when the function is called, NULL is returned. size_t strlen( const char *s ); Determines the length of string s. The number of characters preceding the terminating null character is returned.
  • 101. Structure Definitions  Structures  Aggregate data types built using elements of other types struct Time { int hour; int minute; int second; }; Structure member naming  In same struct: must have unique names  In different structs: can share name struct definition must end with semicolon Structure tag Structure members Structure
  • 102. Structure Definitions  Self-referential structure  Structure member cannot be instance of enclosing struct  Structure member can be pointer to instance of enclosing struct (self-referential structure)  Used for linked lists, queues, stacks and trees  struct definition  Creates new data type used to declare variables  Structure variables declared like variables of other types  Examples:  Time timeObject;  Time timeArray[ 10 ];  Time *timePtr;  Time &timeRef = timeObject;
  • 103. Accessing Structure Members  Member access operators  Dot operator (.) for structure and class members  Arrow operator (->) for structure and class members via pointer to object  Print member hour of timeObject: cout << timeObject.hour; OR timePtr = &timeObject; cout << timePtr->hour;  timePtr->hour same as ( *timePtr ).hour  Parentheses required * lower precedence than .
  • 104. Implementing a User-Defined Type Time with a struct  Default: structures passed by value  Pass structure by reference  Avoid overhead of copying structure  C-style structures  No “interface”  If implementation changes, all programs using that struct must change accordingly  Cannot print as unit  Must print/format member by member  Cannot compare in entirety  Must compare member by member
  • 105. 1 // Example 7 2 // Create a structure, set its members, and print it. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setfill; 11 using std::setw; 12 13 // structure definition 14 struct Time { 15 int hour; // 0-23 (24-hour clock format) 16 int minute; // 0-59 17 int second; // 0-59 18 19 }; // end struct Time 20 21 void printUniversal( const Time & ); // prototype 22 void printStandard( const Time & ); // prototype 23 Define structure type Time with three integer members. Pass references to constant Time objects to eliminate copying overhead.
  • 106. Class  Classes(keyword class)  Model objects  Attributes (data members)  Behaviors (member functions) Methods Invoked in response to messages  Member access specifiers: public, Private, protected:  Constructor function  Special member function  Initializes data members  Same name as class  Called when object instantiated  Several constructors  Function overloading  No return type
  • 107. Implementing a Time Abstract Data Type with a class  Objects of class  After class definition  Class name new type specifier  Object, array, pointer and reference declarations Member functions defined outside class Time sunset; // object of type Time Time arrayOfTimes[ 5 ]; // array of Time objects Time *pointerToTime; // pointer to a Time object Time &dinnerTime = sunset; // reference to a Time object Class name becomes new type specifier. Binary scope resolution (::) ReturnType ClassName::MemberFunctionName( ){…} Member functions defined inside class Do not need scope resolution operator, class name Compiler attempts inline Outside class, inline explicitly with keyword inline
  • 108. 1 // Example 8 2 // Time class. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setfill; 11 using std::setw; 12 13 // Time abstract data type (ADT) definition 14 class Time { 15 16 public: 17 Time(); // constructor 18 void setTime( int, int, int ); // set hour, minute, second 19 void printUniversal(); // print universal-time format 20 void printStandard(); // print standard-time format 21 Define class Time.
  • 109. 22 private: 23 int hour; // 0 - 23 (24-hour clock format) 24 int minute; // 0 - 59 25 int second; // 0 - 59 26 27 }; // end class Time 28 29 // Time constructor initializes each data member to zero and 30 // ensures all Time objects start in a consistent state 31 Time::Time() 32 { 33 hour = minute = second = 0; 34 35 } // end Time constructor 36 37 // set new Time value using universal time, perform validity 38 // checks on the data values and set invalid values to zero 39 void Time::setTime( int h, int m, int s ) 40 { 41 hour = ( h >= 0 && h < 24 ) ? h : 0; 42 minute = ( m >= 0 && m < 60 ) ? m : 0; 43 second = ( s >= 0 && s < 60 ) ? s : 0; 44 45 } // end function setTime 46 Constructor initializes private data members to 0. public member function checks parameter values for validity before setting private data members.
  • 110. 47 // print Time in universal format 48 void Time::printUniversal() 49 { 50 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 51 << setw( 2 ) << minute << ":" 52 << setw( 2 ) << second; 53 54 } // end function printUniversal 55 56 // print Time in standard format 57 void Time::printStandard() 58 { 59 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) 60 << ":" << setfill( '0' ) << setw( 2 ) << minute 61 << ":" << setw( 2 ) << second 62 << ( hour < 12 ? " AM" : " PM" ); 63 64 } // end function printStandard 65 66 int main() 67 { 68 Time t; // instantiate object t of class Time 69 Declare variable t to be object of class Time. No arguments (implicitly “know” purpose is to print data members); member function calls more concise.
  • 111. 70 // output Time object t's initial values 71 cout << "The initial universal time is "; 72 t.printUniversal(); // 00:00:00 73 74 cout << "nThe initial standard time is "; 75 t.printStandard(); // 12:00:00 AM 76 77 t.setTime( 13, 27, 6 ); // change time 78 79 // output Time object t's new values 80 cout << "nnUniversal time after setTime is "; 81 t.printUniversal(); // 13:27:06 82 83 cout << "nStandard time after setTime is "; 84 t.printStandard(); // 1:27:06 PM 85 86 t.setTime( 99, 99, 99 ); // attempt invalid settings 87 88 // output t's values after specifying invalid values 89 cout << "nnAfter attempting invalid settings:" 90 << "nUniversal time: "; 91 t.printUniversal(); // 00:00:00 92 Invoke public member functions to print time. Set data members using public member function. Attempt to set data members to invalid values using public member function.
  • 112. 93 cout << "nStandard time: "; 94 t.printStandard(); // 12:00:00 AM 95 cout << endl; 96 97 return 0; 98 99 } // end main The initial universal time is 00:00:00 The initial standard time is 12:00:00 AM Universal time after setTime is 13:27:06 Standard time after setTime is 1:27:06 PM After attempting invalid settings: Universal time: 00:00:00 Standard time: 12:00:00 AM Data members set to 0 after attempting invalid settings.
  • 113. Classes  Destructors  Same name as class  Preceded with tilde (~)  No arguments  Cannot be overloaded  Performs “termination housekeeping”  Advantages of using classes  Simplify programming  Interfaces  Hide implementation  Software reuse  Composition (aggregation) Class objects included as members of other classes  Inheritance New classes derived from old
  • 114. Class Scope and Accessing Class Members  Class scope  Data members, member functions  Within class scope  Class members Immediately accessible by all member functions Referenced by name  Outside class scope  Referenced through handles Object name, reference to object, pointer to object  File scope  Nonmember functions
  • 115. Class Scope and Accessing Class Members Function scope Variables declared in member function Only known to function Variables with same name as class-scope variables  Class-scope variable “hidden” Access with scope resolution operator (::) ClassName::classVariableName Variables only known to function they are defined in Variables are destroyed after function completion Operators to access class members Identical to those for structs Dot member selection operator (.)  Object  Reference to object Arrow member selection operator (->)  Pointers
  • 116. 1 // Example 9 2 // Demonstrating the class member access operators . and -> 3 // 4 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! 5 #include <iostream> 6 7 using std::cout; 8 using std::endl; 9 10 // class Count definition 11 class Count { 12 13 public: 14 int x; 15 16 void print() 17 { 18 cout << x << endl; 19 } 20 21 }; // end class Count 22 Data member x public to illustrate class member access operators; typically data members private.
  • 117. Separating Interface from Implementation Separating interface from implementation Advantage: Easier to modify programs Disadvantage  Header files Portions of implementation: Inline member functions Hints about other implementation: private members  Can hide more with proxy class Header files Class definitions and function prototypes Included in each file using class  #include File extension .h Source-code files Member function definitions Same base name  Convention Compiled and linked
  • 118. Controlling Access to Members  Access modes  private  Default access mode  Accessible to member functions and friends  public  Accessible to any function in program with handle to class object  protected (later)  Class member access  Default private  Explicitly set to private, public, protected  struct member access  Default public  Explicitly set to private, public, protected
  • 119. Access Functions and Utility Functions  Access to class’s private data  Controlled with access functions (accessor methods)  Get function - Read private data  Set function - Modify private data  Access functions  public  Read/display data  Predicate functions  Check conditions  Utility functions (helper functions)  private  Support operation of public member functions  Not intended for direct client use
  • 120. 1 // Example 10 2 // SalesPerson class definition. 3 // Member functions defined in salesp.cpp. 4 #ifndef SALESP_H 5 #define SALESP_H 6 7 class SalesPerson { 8 9 public: 10 SalesPerson(); // constructor 11 void getSalesFromUser(); // input sales from keyboard 12 void setSales( int, double ); // set sales for a month 13 void printAnnualSales(); // summarize and print sales 14 15 private: 16 double totalAnnualSales(); // utility function 17 double sales[ 12 ]; // 12 monthly sales figures 18 19 }; // end class SalesPerson 20 21 #endif Set access function performs validity checks. private utility function.
  • 121. 25 // get 12 sales figures from the user at the keyboard 26 void SalesPerson::getSalesFromUser() 27 { 28 double salesFigure; 29 30 for ( int i = 1; i <= 12; i++ ) { 31 cout << "Enter sales amount for month " << i << ": "; 32 cin >> salesFigure; 33 setSales( i, salesFigure ); 34 35 } // end for 36 37 } // end function getSalesFromUser 38 39 // set one of the 12 monthly sales figures; function subtracts 40 // one from month value for proper subscript in sales array 41 void SalesPerson::setSales( int month, double amount ) 42 { 43 // test for valid month and amount values 44 if ( month >= 1 && month <= 12 && amount > 0 ) 45 sales[ month - 1 ] = amount; // adjust for subscripts 0-11 46 47 else // invalid month or amount value 48 cout << "Invalid month or sales figure" << endl; Set access function performs validity checks.
  • 122. Initializing Class Objects: Constructors Constructors Initialize data members; no return type  Or can set later Same name as class Can specify default arguments Default constructors  Defaults all arguments OR  Explicitly requires no arguments  Can be invoked with no arguments  Only one per class Initializers Passed as arguments to constructor In parentheses to right of class name before semicolon Class-type ObjectName( value1,value2,…);
  • 123. 1 // Example 11 2 // Declaration of class Time. 3 // Member functions defined in time2.cpp. 4 5 // prevent multiple inclusions of header file 6 #ifndef TIME2_H 7 #define TIME2_H 8 9 // Time abstract data type definition 10 class Time { 11 12 public: 13 Time( int = 0, int = 0, int = 0); // default constructor 14 void setTime( int, int, int ); // set hour, minute, second 15 void printUniversal(); // print universal-time format 16 void printStandard(); // print standard-time format 17 18 private: 19 int hour; // 0 - 23 (24-hour clock format) 20 int minute; // 0 - 59 21 int second; // 0 - 59 22 23 }; // end class Time 24 25 #endif Default constructor specifying all arguments.
  • 124. 1 // Example 12 2 // Member-function definitions for class Time. 3 #include <iostream> 4 5 using std::cout; 6 7 #include <iomanip> 8 9 using std::setfill; 10 using std::setw; 11 12 // include definition of class Time from time2.h 13 #include "time2.h" 14 15 // Time constructor initializes each data member to zero; 16 // ensures all Time objects start in a consistent state 17 Time::Time( int hr, int min, int sec ) 18 { 19 setTime( hr, min, sec ); // validate and set time 20 21 } // end Time constructor 22 Constructor calls setTime to validate passed (or default) values.
  • 125. 23 // set new Time value using universal time, perform validity 24 // checks on the data values and set invalid values to zero 25 void Time::setTime( int h, int m, int s ) 26 { 27 hour = ( h >= 0 && h < 24 ) ? h : 0; 28 minute = ( m >= 0 && m < 60 ) ? m : 0; 29 second = ( s >= 0 && s < 60 ) ? s : 0; 30 31 } // end function setTime 32 33 // print Time in universal format 34 void Time::printUniversal() 35 { 36 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 37 << setw( 2 ) << minute << ":" 38 << setw( 2 ) << second; 39 40 } // end function printUniversal 41
  • 126. 1 // Example 13 2 // Demonstrating a default constructor for class Time. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // include definition of class Time from time2.h 9 #include "time2.h" 10 11 int main() 12 { 13 Time t1; // all arguments defaulted 14 Time t2( 2 ); // minute and second defaulted 15 Time t3( 21, 34 ); // second defaulted 16 Time t4( 12, 25, 42 ); // all values specified 17 Time t5( 27, 74, 99 ); // all bad values specified 18 19 cout << "Constructed with:nn" 20 << "all default arguments:n "; 21 t1.printUniversal(); // 00:00:00 22 cout << "n "; 23 t1.printStandard(); // 12:00:00 AM 24 Initialize Time objects using default arguments. Initialize Time object with invalid values; validity checking will set values to 0.
  • 127. 25 cout << "nnhour specified; default minute and second:n "; 26 t2.printUniversal(); // 02:00:00 27 cout << "n "; 28 t2.printStandard(); // 2:00:00 AM 29 30 cout << "nnhour and minute specified; default second:n "; 31 t3.printUniversal(); // 21:34:00 32 cout << "n "; 33 t3.printStandard(); // 9:34:00 PM 34 35 cout << "nnhour, minute, and second specified:n "; 36 t4.printUniversal(); // 12:25:42 37 cout << "n "; 38 t4.printStandard(); // 12:25:42 PM 39 40 cout << "nnall invalid values specified:n "; 41 t5.printUniversal(); // 00:00:00 42 cout << "n "; 43 t5.printStandard(); // 12:00:00 AM 44 cout << endl; 45 46 return 0; 47 48 } // end main t5 constructed with invalid arguments; values set to 0.
  • 128. Destructors  Destructors  Special member function  Same name as class preceded with tilde (~)  No arguments; No return value  Cannot be overloaded  Performs “termination housekeeping”  Before system reclaims object’s memory Reuse memory for new objects  No explicit destructor  Compiler creates “empty destructor”  Constructors and destructors - Called implicitly by compiler  Order of function calls  Depends on when execution enters and exits scope of objects  Generally, destructor calls reverse order of constructor calls
  • 129. When Constructors and Destructors Are Called  Global scope objects  Constructors - Before any other function (including main)  Destructors When main terminates (or exit function called) Not called if program terminates with abort  Automatic local objects  Constructors - When objects defined & each time execution enters scope  Destructors When objects leave scope  Execution exits block in which object defined Not called if program ends with exit or abort  static local objects  Constructors Exactly once When execution reaches point where object defined  Destructors When main terminates or exit function called Not called if program ends with abort
  • 130. 1 // Example 14 2 // Demonstrating the order in which constructors and 3 // destructors are called. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 // include CreateAndDestroy class definition from create.h 10 #include "create.h" 11 12 void create( void ); // prototype 13 14 // global object 15 CreateAndDestroy first( 1, "(global before main)" ); 16 17 int main() 18 { 19 cout << "nMAIN FUNCTION: EXECUTION BEGINS" << endl; 20 21 CreateAndDestroy second( 2, "(local automatic in main)" ); 22 23 static CreateAndDestroy third( 24 3, "(local static in main)" ); 25 Create variable with global scope. Create local automatic object. Create static local object.
  • 131. 26 create(); // call function to create objects 27 28 cout << "nMAIN FUNCTION: EXECUTION RESUMES" << endl; 29 30 CreateAndDestroy fourth( 4, "(local automatic in main)" ); 31 32 cout << "nMAIN FUNCTION: EXECUTION ENDS" << endl; 33 34 return 0; 35 36 } // end main 37 38 // function to create objects 39 void create( void ) 40 { 41 cout << "nCREATE FUNCTION: EXECUTION BEGINS" << endl; 42 43 CreateAndDestroy fifth( 5, "(local automatic in create)" ); 44 45 static CreateAndDestroy sixth( 46 6, "(local static in create)" ); 47 48 CreateAndDestroy seventh( 49 7, "(local automatic in create)" ); 50 cout << "nCREATE FUNCTION: EXECUTION ENDS" << endl; 52 53 } // end function create Create local automatic objects. Create local automatic object. Create local automatic object in function. Create static local object in function. Create local automatic object in function.
  • 132. Object 1 constructor runs (global before main) MAIN FUNCTION: EXECUTION BEGINS Object 2 constructor runs (local automatic in main) Object 3 constructor runs (local static in main) CREATE FUNCTION: EXECUTION BEGINS Object 5 constructor runs (local automatic in create) Object 6 constructor runs (local static in create) Object 7 constructor runs (local automatic in create) CREATE FUNCTION: EXECUTION ENDS Object 7 destructor runs (local automatic in create) Object 5 destructor runs (local automatic in create) MAIN FUNCTION: EXECUTION RESUMES Object 4 constructor runs (local automatic in main) MAIN FUNCTION: EXECUTION ENDS Object 4 destructor runs (local automatic in main) Object 2 destructor runs (local automatic in main) Object 6 destructor runs (local static in create) Object 3 destructor runs (local static in main) Object 1 destructor runs (global before main) Destructors for local automatic objects in main called in reverse order of constructors. Local static object exists until program termination.Global object constructed before main execution and destroyed last. Local automatic objects destroyed after function execution ends in reverse order of construction. Local static object constructed on first function call and destroyed after main execution ends.
  • 133. Using Set and Get Functions  Set functions  Perform validity checks before modifying private data  Notify if invalid values  Indicate with return values  Get functions  “Query” functions  Control format of data returned
  • 134. Subtle Trap: Returning a Reference to a private Data Member  Reference to object  &pRef = p;  Alias for name of object  Lvalue  Can receive value in assignment statement Changes original object  Returning references  public member functions can return non-const references to private data members  Client able to modify private data members
  • 135. 1 // Example 15 2 // Declaration of class Time. 3 // Member functions defined in time4.cpp 4 5 // prevent multiple inclusions of header file 6 #ifndef TIME4_H 7 #define TIME4_H 8 9 class Time { 10 11 public: 12 Time( int = 0, int = 0, int = 0 ); 13 void setTime( int, int, int ); 14 int getHour(); 15 16 int &badSetHour( int ); // DANGEROUS reference return 17 18 private: 19 int hour; 20 int minute; 21 int second; 22 23 }; // end class Time 24 25 #endif Function to demonstrate effects of returning reference to private data member.
  • 136. 25 // return hour value 26 int Time::getHour() 27 { 28 return hour; 29 30 } // end function getHour 31 32 // POOR PROGRAMMING PRACTICE: 33 // Returning a reference to a private data member. 34 int &Time::badSetHour( int hh ) 35 { 36 hour = ( hh >= 0 && hh < 24 ) ? hh : 0; 37 38 return hour; // DANGEROUS reference return 39 40 } // end function badSetHour Return reference to private data member hour.
  • 137. 1 // Example 16 2 // Demonstrating a public member function that 3 // returns a reference to a private data member. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 // include definition of class Time from time4.h 10 #include "time4.h" 11 12 int main() 13 { 14 Time t; 15 16 // store in hourRef the reference returned by badSetHour 17 int &hourRef = t.badSetHour( 20 ); 18 19 cout << "Hour before modification: " << hourRef; 20 21 // use hourRef to set invalid value in Time object t 22 hourRef = 30; 23 24 cout << "nHour after modification: " << t.getHour(); 25 badSetHour returns reference to private data member hour. Reference allows setting of private data member hour.
  • 138. 26 // Dangerous: Function call that returns 27 // a reference can be used as an lvalue! 28 t.badSetHour( 12 ) = 74; 29 30 cout << "nn*********************************n" 31 << "POOR PROGRAMMING PRACTICE!!!!!!!!n" 32 << "badSetHour as an lvalue, Hour: " 33 << t.getHour() 34 << "n*********************************" << endl; 35 36 return 0; 37 38 } // end main Hour before modification: 20 Hour after modification: 30 ********************************* POOR PROGRAMMING PRACTICE!!!!!!!! badSetHour as an lvalue, Hour: 74 ********************************* Can use function call as lvalue to set invalid value. Returning reference allowed invalid setting of private data member hour.
  • 139. Default Memberwise Assignment  Assigning objects  Assignment operator (=)  Can assign one object to another of same type  Default: memberwise assignment Each right member assigned individually to left member  Passing, returning objects  Objects passed as function arguments  Objects returned from functions  Default: pass-by-value  Copy of object passed, returned Copy constructor  Copy original values into new object
  • 140. 1 // Example 17 2 // Demonstrating that class objects can be assigned 3 // to each other using default memberwise assignment. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 // class Date definition 10 class Date { 11 12 public: 13 Date( int = 1, int = 1, int = 1990 ); // default constructor 14 void print(); 15 16 private: 17 int month; 18 int day; 19 int year; 20 21 }; // end class Date 22
  • 141. Software Reusability  Software reusability  Class libraries  Well-defined  Carefully tested  Well-documented  Portable  Widely available  Speeds development of powerful, high-quality software  Rapid applications development (RAD)  Resulting problems  Cataloging schemes  Licensing schemes  Protection mechanisms
  • 142. const (Constant) Objects and const Member Functions  Keyword const  Specify object not modifiable  Compiler error if attempt to modify const object  Example const Time noon( 12, 0, 0 );  Declares const object noon of class Time  Initializes to 12  const member functions  Member functions for const objects must also be const  Cannot modify object  Specify const in both prototype and definition  Prototype After parameter list  Definition Before beginning left brace
  • 143. const (Constant) Objects and const Member Functions  Constructors and destructors  Cannot be const  Must be able to modify objects  Constructor Initializes objects  Destructor Performs termination housekeeping  Member initializer syntax  Initializing with member initializer syntax  Can be used for All data members  Must be used for const data members Data members that are references
  • 144. 1 // Example 18 2 // Using a member initializer to initialize a 3 // constant of a built-in data type. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 class Increment { 10 11 public: 12 Increment( int c = 0, int i = 1 ); // default constructor 13 14 void addIncrement() 15 { 16 count += increment; 17 18 } // end function addIncrement 19 20 void print() const; // prints count and increment 21
  • 145. 22 private: 23 int count; 24 const int increment; // const data member 25 26 }; // end class Increment 27 28 // constructor 29 Increment::Increment( int c, int i ) 30 : count( c ), // initializer for non-const member 31 increment( i ) // required initializer for const member 32 { 33 // empty body 34 35 } // end Increment constructor 36 37 // print count and increment values 38 void Increment::print() const 39 { 40 cout << "count = " << count 41 << ", increment = " << increment << endl; 42 43 } // end function print 44 Declare increment as const data member. Member initializer list separated from parameter list by colon. Member initializer syntax can be used for non-const data member count. Member initializer syntax must be used for const data member increment. Member initializer consists of data member name (increment) followed by parentheses containing initial value (c).
  • 146. Composition: Objects as Members of Classes  Composition  Class has objects of other classes as members  Construction of objects  Member objects constructed in order declared  Not in order of constructor’s member initializer list  Constructed before enclosing class objects (host objects)
  • 147. 1 // Example 19 2 // Date class definition. 3 // Member functions defined in date1.cpp 4 #ifndef DATE1_H 5 #define DATE1_H 6 7 class Date { 8 9 public: 10 Date( int = 1, int = 1, int = 1900 ); // default constructor 11 void print() const; // print date in month/day/year format 12 ~Date(); // provided to confirm destruction order 13 14 private: 15 int month; // 1-12 (January-December) 16 int day; // 1-31 based on month 17 int year; // any year 18 19 // utility function to test proper day for month and year 20 int checkDay( int ) const; 21 22 }; // end class Date 23 24 #endif Note no constructor with parameter of type Date. Recall compiler provides default copy constructor.
  • 148. 1 // EXAMPLE 20 2 // Employee class definition. 3 // Member functions defined in employee1.cpp. 4 #ifndef EMPLOYEE1_H 5 #define EMPLOYEE1_H 6 7 // include Date class definition from date1.h 8 #include "date1.h" 9 10 class Employee { 11 12 public: 13 Employee( 14 const char *, const char *, const Date &, const Date & ); 15 16 void print() const; 17 ~Employee(); // provided to confirm destruction order 18 19 private: 20 char firstName[ 25 ]; 21 char lastName[ 25 ]; 22 const Date birthDate; // composition: member object 23 const Date hireDate; // composition: member object 24 25 }; // end class Employee Using composition; Employee object contains Date objects as data members.
  • 149. 13 // constructor uses member initializer list to pass initializer 14 // values to constructors of member objects birthDate and 15 // hireDate [Note: This invokes the so-called "default copy 16 // constructor" which the C++ compiler provides implicitly.] 17 Employee::Employee( const char *first, const char *last, 18 const Date &dateOfBirth, const Date &dateOfHire ) 19 : birthDate( dateOfBirth ), // initialize birthDate 20 hireDate( dateOfHire ) // initialize hireDate 21 { 22 // copy first into firstName and be sure that it fits 23 int length = strlen( first ); 24 length = ( length < 25 ? length : 24 ); 25 strncpy( firstName, first, length ); 26 firstName[ length ] = '0'; 27 28 // copy last into lastName and be sure that it fits 29 length = strlen( last ); 30 length = ( length < 25 ? length : 24 ); 31 strncpy( lastName, last, length ); 32 lastName[ length ] = '0'; 33 34 // output Employee object to show when constructor is called 35 cout << "Employee object constructor: " 36 << firstName << ' ' << lastName << endl; 37 Member initializer syntax to initialize Date data members birthDate and hireDate; compiler uses default copy constructor. Output to show timing of constructors.
  • 150. 1 // Example 21 2 // Demonstrating composition--an object with member objects. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include "employee1.h" // Employee class definition 9 10 int main() 11 { 12 Date birth( 7, 24, 1949 ); 13 Date hire( 3, 12, 1988 ); 14 Employee manager( "Bob", "Jones", birth, hire ); 15 16 cout << 'n'; 17 manager.print(); 18 19 cout << "nTest Date constructor with invalid values:n"; 20 Date lastDayOff( 14, 35, 1994 ); // invalid month and day 21 cout << endl; 22 23 return 0; 24 25 } // end main Create Date objects to pass to Employee constructor.
  • 151. friend Functions and friend Classes  friend function  Defined outside class’s scope  Right to access non-public members  Declaring friends  Function  Precede function prototype with keyword friend  Want to make all member functions of class ClassTwo as friends of class ClassOne  Place declaration of form friend class ClassTwo; in ClassOne definition
  • 152. friend Functions and friend Classes  Properties of friendship  Friendship granted, not taken  Class B friend of class A Class A must explicitly declare class B friend  Not symmetric  Class B friend of class A  Class A not necessarily friend of class B  Not transitive  Class A friend of class B  Class B friend of class C  Class A not necessarily friend of Class C
  • 153. 1 // Example 22 2 // Friends can access private members of a class. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // Count class definition 9 class Count { 10 friend void setX( Count &, int ); // friend declaration 11 12 public: 13 14 // constructor 15 Count() 16 : x( 0 ) // initialize x to 0 17 { 18 // empty body 19 20 } // end Count constructor 21 Precede function prototype with keyword friend.
  • 154. 22 // output x 23 void print() const 24 { 25 cout << x << endl; 26 27 } // end function print 28 29 private: 30 int x; // data member 31 32 }; // end class Count 33 34 // function setX can modify private data of Count 35 // because setX is declared as a friend of Count 36 void setX( Count &c, int val ) 37 { 38 c.x = val; // legal: setX is a friend of Count 39 40 } // end function setX 41 Pass Count object since C- style, standalone function. Since setX friend of Count, can access and modify private data member x.
  • 155. 42 int main() 43 { 44 Count counter; // create Count object 45 46 cout << "counter.x after instantiation: "; 47 counter.print(); 48 49 setX( counter, 8 ); // set x with a friend 50 51 cout << "counter.x after call to setX friend function: "; 52 counter.print(); 53 54 return 0; 55 56 } // end main counter.x after instantiation: 0 counter.x after call to setX friend function: 8 Use friend function to access and modify private data member x.
  • 156. Using the this Pointer  this pointer  Allows object to access own address  Not part of object itself  Implicit argument to non-static member function call  Implicitly reference member data and functions  Type of this pointer depends on  Type of object  Whether member function is const  In non-const member function of Employee this has type Employee * const  Constant pointer to non-constant Employee object  In const member function of Employee this has type const Employee * const  Constant pointer to constant Employee object
  • 157. 1 // Example 23 2 // Using the this pointer to refer to object members. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 class Test { 9 10 public: 11 Test( int = 0 ); // default constructor 12 void print() const; 13 14 private: 15 int x; 16 17 }; // end class Test 18 19 // constructor 20 Test::Test( int value ) 21 : x( value ) // initialize x to value 22 { 23 // empty body 24 25 } // end Test constructor
  • 158. 26 27 // print x using implicit and explicit this pointers; 28 // parentheses around *this required 29 void Test::print() const 30 { 31 // implicitly use this pointer to access member x 32 cout << " x = " << x; 33 34 // explicitly use this pointer to access member x 35 cout << "n this->x = " << this->x; 36 37 // explicitly use dereferenced this pointer and 38 // the dot operator to access member x 39 cout << "n(*this).x = " << ( *this ).x << endl; 40 41 } // end function print 42 43 int main() 44 { 45 Test testObject( 12 ); 46 47 testObject.print(); 48 49 return 0; 50 Implicitly use this pointer; only specify name of data member (x). Explicitly use this pointer with arrow operator. Explicitly use this pointer; dereference this pointer first, then use dot operator. 51 } // end main x = 12 this->x = 12 (*this).x = 12
  • 159. Using the this Pointer  Cascaded member function calls  Multiple functions invoked in same statement  Function returns reference pointer to same object { return *this; }  Other functions operate on that pointer  Functions that do not return references must be called last
  • 160. 1 // Example 24 2 // Cascading member function calls. 3 4 // Time class definition. 5 // Member functions defined in time6.cpp. 6 #ifndef TIME6_H 7 #define TIME6_H 8 9 class Time { 10 11 public: 12 Time( int = 0, int = 0, int = 0 ); // default constructor 13 14 // set functions 15 Time &setTime( int, int, int ); // set hour, minute, second 16 Time &setHour( int ); // set hour 17 Time &setMinute( int ); // set minute 18 Time &setSecond( int ); // set second 19 20 // get functions (normally declared const) 21 int getHour() const; // return hour 22 int getMinute() const; // return minute 23 int getSecond() const; // return second 24 Set functions return reference to Time object to enable cascaded member function calls.
  • 161. 25 // print functions (normally declared const) 26 void printUniversal() const; // print universal time 27 void printStandard() const; // print standard time 28 29 private: 30 int hour; // 0 - 23 (24-hour clock format) 31 int minute; // 0 - 59 32 int second; // 0 - 59 33 34 }; // end class Time 35 36 #endif
  • 162. 1 // Example 25 2 // Member-function definitions for Time class. 3 #include <iostream> 4 5 using std::cout; 6 7 #include <iomanip> 8 9 using std::setfill; 10 using std::setw; 11 12 #include "time6.h" // Time class definition 13 14 // constructor function to initialize private data; 15 // calls member function setTime to set variables; 16 // default values are 0 (see class definition) 17 Time::Time( int hr, int min, int sec ) 18 { 19 setTime( hr, min, sec ); 20 21 } // end Time constructor 22
  • 163. 23 // set values of hour, minute, and second 24 Time &Time::setTime( int h, int m, int s ) 25 { 26 setHour( h ); 27 setMinute( m ); 28 setSecond( s ); 29 30 return *this; // enables cascading 31 32 } // end function setTime 33 34 // set hour value 35 Time &Time::setHour( int h ) 36 { 37 hour = ( h >= 0 && h < 24 ) ? h : 0; 38 39 return *this; // enables cascading 40 41 } // end function setHour 42 Return *this as reference to enable cascaded member function calls. Return *this as reference to enable cascaded member function calls.
  • 164. 43 // set minute value 44 Time &Time::setMinute( int m ) 45 { 46 minute = ( m >= 0 && m < 60 ) ? m : 0; 47 48 return *this; // enables cascading 49 50 } // end function setMinute 51 52 // set second value 53 Time &Time::setSecond( int s ) 54 { 55 second = ( s >= 0 && s < 60 ) ? s : 0; 56 57 return *this; // enables cascading 58 59 } // end function setSecond 60 61 // get hour value 62 int Time::getHour() const 63 { 64 return hour; 65 66 } // end function getHour 67 Return *this as reference to enable cascaded member function calls. Return *this as reference to enable cascaded member function calls.
  • 165. 68 // get minute value 69 int Time::getMinute() const 70 { 71 return minute; 72 73 } // end function getMinute 74 75 // get second value 76 int Time::getSecond() const 77 { 78 return second; 79 80 } // end function getSecond 81 82 // print Time in universal format 83 void Time::printUniversal() const 84 { 85 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 86 << setw( 2 ) << minute << ":" 87 << setw( 2 ) << second; 88 89 } // end function printUniversal 90
  • 166. 91 // print Time in standard format 92 void Time::printStandard() const 93 { 94 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) 95 << ":" << setfill( '0' ) << setw( 2 ) << minute 96 << ":" << setw( 2 ) << second 97 << ( hour < 12 ? " AM" : " PM" ); 98 99 } // end function printStandard
  • 167. 1 // Example 26 2 // Cascading member function calls with the this pointer. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include "time6.h" // Time class definition 9 10 int main() 11 { 12 Time t; 13 14 // cascaded function calls 15 t.setHour( 18 ).setMinute( 30 ).setSecond( 22 ); 16 17 // output time in universal and standard formats 18 cout << "Universal time: "; 19 t.printUniversal(); 20 21 cout << "nStandard time: "; 22 t.printStandard(); 23 24 cout << "nnNew standard time: "; 25 Cascade member function calls; recall dot operator associates from left to right.
  • 168. 26 // cascaded function calls 27 t.setTime( 20, 20, 20 ).printStandard(); 28 29 cout << endl; 30 31 return 0; 32 33 } // end main Universal time: 18:30:22 Standard time: 6:30:22 PM New standard time: 8:20:20 PM Function call to printStandard must appear last; printStandard does not return reference to t.
  • 169. Dynamic Memory Management with Operators new and delete Dynamic memory management Control allocation and deallocation of memory Operators new and delete  Include standard header <new> new Time *timePtr; timePtr = new Time; Creates object of proper size for type Time  Error if no space in memory for object Calls default constructor for object Returns pointer of specified type Providing initializers double *ptr = new double( 3.14159 ); Time *timePtr = new Time( 12, 0, 0 ); Allocating arrays int *gradesArray = new int[ 10 ];
  • 170. Dynamic Memory Management with Operators new and delete  delete  Destroy dynamically allocated object and free space  Consider delete timePtr;  Operator delete  Calls destructor for object  Deallocates memory associated with object Memory can be reused to allocate other objects  Deallocating arrays delete [] gradesArray; Deallocates array to which gradesArray points  If pointer to array of objects  First calls destructor for each object in array  Then deallocates memory
  • 171. static Class Members  static class variable  “Class-wide” data  Property of class, not specific object of class  Efficient when single copy of data is enough  Only the static variable has to be updated  May seem like global variables, but have class scope  Only accessible to objects of same class  Initialized exactly once at file scope  Exist even if no objects of class exist  Can be public, private or protected
  • 172. static Class Members Accessing static class variables  Accessible through any object of class  public static variables  Can also be accessed using binary scope resolution operator(::) Employee::count  private static variables  When no class member objects exist: Can only be accessed via public static member function Employee::getCount() static member functions  Cannot access non-static data or functions  No this pointer for static functions  static data members and static member functions exist independent of objects
  • 173. 1 // Example 26 2 // Employee class definition. 3 #ifndef EMPLOYEE2_H 4 #define EMPLOYEE2_H 5 6 class Employee { 7 8 public: 9 Employee( const char *, const char * ); // constructor 10 ~Employee(); // destructor 11 const char *getFirstName() const; // return first name 12 const char *getLastName() const; // return last name 13 14 // static member function 15 static int getCount(); // return # objects instantiated 16 17 private: 18 char *firstName; 19 char *lastName; 20 21 // static data member 22 static int count; // number of objects instantiated 23 24 }; // end class Employee 25 static member function can only access static data members and member functions. static data member is class-wide data.
  • 174. 1 // Example 27 2 // Member-function definitions for class Employee. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <new> // C++ standard new operator 9 #include <cstring> // strcpy and strlen prototypes 10 11 #include "employee2.h" // Employee class definition 12 13 // define and initialize static data member 14 int Employee::count = 0; 15 16 // define static member function that returns number of 17 // Employee objects instantiated 18 int Employee::getCount() 19 { 20 return count; 21 22 } // end static function getCount Initialize static data member exactly once at file scope. static member function accesses static data member count.
  • 175. 23 24 // constructor dynamically allocates space for 25 // first and last name and uses strcpy to copy 26 // first and last names into the object 27 Employee::Employee( const char *first, const char *last ) 28 { 29 firstName = new char[ strlen( first ) + 1 ]; 30 strcpy( firstName, first ); 31 32 lastName = new char[ strlen( last ) + 1 ]; 33 strcpy( lastName, last ); 34 35 ++count; // increment static count of employees 36 37 cout << "Employee constructor for " << firstName 38 << ' ' << lastName << " called." << endl; 39 40 } // end Employee constructor 41 42 // destructor deallocates dynamically allocated memory 43 Employee::~Employee() 44 { 45 cout << "~Employee() called for " << firstName 46 << ' ' << lastName << endl; 47 new operator dynamically allocates space. Use static data member to store total count of employees.
  • 176. 48 delete [] firstName; // recapture memory 49 delete [] lastName; // recapture memory 50 51 --count; // decrement static count of employees 52 53 } // end destructor ~Employee 54 55 // return first name of employee 56 const char *Employee::getFirstName() const 57 { 58 // const before return type prevents client from modifying 59 // private data; client should copy returned string before 60 // destructor deletes storage to prevent undefined pointer 61 return firstName; 62 63 } // end function getFirstName 64 65 // return last name of employee 66 const char *Employee::getLastName() const 67 { 68 // const before return type prevents client from modifying 69 // private data; client should copy returned string before 70 // destructor deletes storage to prevent undefined pointer 71 return lastName; 72 73 } // end function getLastName Operator delete deallocates memory. Use static data member to store total count of employees.
  • 177. Data Abstraction and Information Hiding  Information hiding  Classes hide implementation details from clients  Example: stack data structure  Data elements added (pushed) onto top  Data elements removed (popped) from top  Last-in, first-out (LIFO) data structure  Client only wants LIFO data structure Does not care how stack implemented  Data abstraction  Describe functionality of class independent of implementation
  • 178. Data Abstraction and Information Hiding  Abstract data types (ADTs)  Approximations/models of real-world concepts and behaviors  int, float are models for a numbers  Data representation  Operations allowed on those data  C++ extensible  Standard data types cannot be changed, but new data types can be created
  • 179. Proxy Classes  Proxy class  Hide implementation details of another class  Knows only public interface of class being hidden  Enables clients to use class’s services without giving access to class’s implementation  Forward class declaration  Used when class definition only uses pointer to another class  Prevents need for including header file  Declares class before referencing  Format: class ClassToLoad;
  • 180. 1 // Example 28 2 // Header file for class Implementation 3 4 class Implementation { 5 6 public: 7 8 // constructor 9 Implementation( int v ) 10 : value( v ) // initialize value with v 11 { 12 // empty body 13 14 } // end Implementation constructor 15 16 // set value to v 17 void setValue( int v ) 18 { 19 value = v; // should validate v 20 21 } // end function setValue 22 public member function. 23 // return value 24 int getValue() const 25 { 26 return value; 27 28 } // end function getValue 29 30 private: 31 int value; 32 33 }; // end class Implementation
  • 181. 1 // Example 29 2 // Header file for interface.cpp 3 4 class Implementation; // forward class declaration 5 6 class Interface { 7 8 public: 9 Interface( int ); 10 void setValue( int ); // same public interface as 11 int getValue() const; // class Implementation 12 ~Interface(); 13 14 private: 15 16 // requires previous forward declaration (line 4) 17 Implementation *ptr; 18 19 }; // end class Interface Provide same public interface as class Implementation; recall setValue and getValue only public member functions. Pointer to Implementation object requires forward class declaration.
  • 182. 1 // Example 30 2 // Definition of class Interface 3 #include "interface.h" // Interface class definition 4 #include "implementation.h" // Implementation class definition 5 6 // constructor 7 Interface::Interface( int v ) 8 : ptr ( new Implementation( v ) ) // initialize ptr 9 { 10 // empty body 11 12 } // end Interface constructor 13 14 // call Implementation's setValue function 15 void Interface::setValue( int v ) 16 { 17 ptr->setValue( v ); 18 19 } // end function setValue 20 Proxy class Interface includes header file for class Implementation. Maintain pointer to underlying Implementation object. Invoke corresponding function on underlying Implementation object.
  • 183. 21 // call Implementation's getValue function 22 int Interface::getValue() const 23 { 24 return ptr->getValue(); 25 26 } // end function getValue 27 28 // destructor 29 Interface::~Interface() 30 { 31 delete ptr; 32 33 } // end destructor ~Interface Invoke corresponding function on underlying Implementation object. Deallocate underlying Implementation object.
  • 184. 1 // Example 30 2 // Hiding a class’s private data with a proxy class. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include "interface.h" // Interface class definition 9 10 int main() 11 { 12 Interface i( 5 ); 13 14 cout << "Interface contains: " << i.getValue() 15 << " before setValue" << endl; 16 17 i.setValue( 10 ); 18 19 cout << "Interface contains: " << i.getValue() 20 << " after setValue" << endl; 21 22 return 0; 23 24 } // end main Interface contains: 5 before setValue Interface contains: 10 after setValue Only include proxy class header file. Create object of proxy class Interface; note no mention of Implementation class. Invoke member functions via proxy class object.
  • 185. Fundamentals of Operator Overloading  Use operators with objects (operator overloading)  Clearer than function calls for certain classes  Operator sensitive to context  Types  Built in (int, char) or user-defined  Can use existing operators with user-defined types  Cannot create new operators  Overloading operators  Create a function for the class  Name function operator followed by symbol  Operator+ for the addition operator +
  • 186. Fundamentals of Operator Overloading  Using operators on a class object  It must be overloaded for that class  Exceptions:  Assignment operator, = May be used without explicit overloading Memberwise assignment between objects  Address operator, & May be used on any class without overloading Returns address of object  Both can be overloaded