Data Structure: Object-Oriented Programming Review
Download
Report
Transcript Data Structure: Object-Oriented Programming Review
Data Structure: Object-Oriented
Programming Review
Fall, 09
1
Pointers and Arrays (1)
Arrays and pointers are closely related
Array name is like constant pointer
We can use array name as pointer
Only that it can be assigned (it’s a constant pointer)
Sometimes, to pass array as function parameter
2
The value saved in an array name is the address of the first
element of the array.
int ArraySum (int array[], int numElements)
int ArraySum (int * array, int numElements)
Accessing array elements with pointers
Assume declarations:
int b[ 5 ];
int *bPtr;
bPtr = b;
Element b[ n ] can be accessed by *( bPtr + n )
Called pointer/offset notation
Addresses
&b[ 3 ] is same as bPtr + 3
Array name can be treated as pointer
b[ 3 ] is same as *( b + 3 )
Pointers can be subscripted (pointer/subscript notation)
3
bPtr[ 3 ] is same as b[ 3 ]
Pointer Arithmetic (1)
Pointer arithmetic
4
Increment/decrement pointer (++ or --)
Add/subtract an integer to/from a pointer (+ or +=,
- or -=)
Pointers may be subtracted from each other
Pointer arithmetic is meaningless unless performed on a
pointer to an array
Passing Arguments to Functions by
Reference with Pointers
Three ways to pass arguments to a function
Pass-by-value
Pass-by-reference with reference arguments
Pass-by-reference with pointer arguments, also called passby-pointer
A function can return only zero or one value
explicitly.
Arguments passed to a function using reference
arguments
5
Function can modify original values of arguments
More than one value “returned” implicitly.
Pass-by-reference With Pointer
Arguments
Simulates pass-by-reference
Use pointers and indirection operator
Pass address of argument using & operator
* operator used as alias/nickname for variable inside of
function
void squareByReference(int *); //function prototype
//function declaration
void squareByReference(int *nPtr)
{
*nPtr = *nPtr * *nPtr;
}
int x;
squareByReference(&x); //call this function
6
Traditional Programming
Procedure based.
A computer program:
a logical procedure that takes input data, processes it, and
produces output data.
The programming challenge was seen as how to finish the
job (solve the problem) in a certain steps.
7
Basic Object Technology Concept
Objects: people, animals, plants, cars.
We study objects’ attributes and observe objects’
behaviors.
Dogs
Attributes : name, color, breed, hungry, age
Behaviors: barking, fetching, wagging tail
Students
Attributes : name, age, SSN, Female/Male, class, major.
Behaviors: taking courses, doing homework, taking exams and so on.
We design computer programs to describe/represent realworld objects or virtual objects.
8
Object-Oriented Programming
Object-Oriented Programming: a collection of
cooperating objects
traditional program: a list of instructions to the computer
In OOP, each object is capable of
9
receiving messages
processing data
sending messages to other objects
Why Object-Oriented Programming?
Reusable
OOP: well designed module could be used on future projects.
Procedural Programming: repeatedly reinvent the wheel.
Maintenance
10
OOP: modular, easy to maintain, interchanged as units without
disassembly of the modules.
Procedural Programming: not well modularized, change the
structure, start from scratch.
Class
A class defines the abstract characteristics of a group
similar objects
A class is a user-defined type.
Attributes (fields or properties)
Behaviors (methods or functions).
Can be used to create objects, i.e., variables of the class type
C++ is an extensible language
Let’s design a class for Dog:
11
The class Dog would consist of features shared by all dogs, such
as breed and fur color (characteristics), and the ability to bark
(behavior).
Question ?
To design a class, we should define attributes and
behaviors.
12
Student class
Computer class
Customer class
A C++ Class
In C++:
13
Data members: variables which are used to represent the
attributes of a class.
Member functions: functions which are used to define the
behaviors of a class.
A C++ Class
A C++ class has two parts:
14
Interface of a Class
Implementation of a Class
The Interface
The interface of a Class like a manual
The interface includes
Describes what the objects of this class can do for us, and also
how to request these services from objects.
Allow compiler to recognize the classes when used elsewhere.
Data Members
Member Function Prototypes
The interface of classA is in a header file : classA.h
15
Example: GradeBook Class
Data Member: int courseNumber;
Member function: void displayMessage();
Header file: GradeBook.h
class GradeBook
{
public: void displayMessage();
private: int courseNumber;
};
16
Access Specifier Labels
public:
private: default access for class
members
The function or data member is available to the public
The function or data member can be used only in member
functions of the same class.
Functions outside the class (main function) or member functions
of other classes could not access them.
As a rule of thumb
17
data members should be declared private
member functions should be declared public.
The Implementation
The implementation of a class defines the member
functions of the class.
The implementation of classA is in a source file :
classA.cpp
The source file includes:
#include statement to include the interface of the class
The implementation of member functions
18
Use binary scope resolution operator (::) to tie each member
function to the class definition.
#include preprocessor directive
Used to include header files
Instructs C++ preprocessor to replace directive with a copy of
the contents of the specified file
Quotes indicate user-defined header files
Preprocessor first looks in current directory
If the file is not found, looks in C++ Standard Library directory
Angle brackets indicate C++ Standard Library
19
Preprocessor looks only in C++ Standard Library directory
Example: GradeBook Class
Source file : GradeBook.cpp
#include <iostream>
using std::cout;
using std::endl;
#include “GradeBook.h”
void GradeBook::displayMessage( )
{
cout << “Welcom to Grade Book for Course No.”
<< courseNumber << endl;
}
20
Compiling Command
Compile the source-code file (GradeBook.cpp) to
create GradeBook’s object code.
Command: g++ -c GradeBook.cpp
Object code : GradeBook.o
To hide the implementation details of GradeBook’s
member functions, only the header file GradeBook.h
and the object code for GradeBook (GradeBook.o)
are provided to these programmers who will use
GradeBook in their codes.
21
Use GradeBook Class: declare an object
Create a GradeBook object
GradeBook myGradeBook;
className objectName;
Memory
courseNumber
Space for data member of
object myGradeBook
22
Use GradeBook Class
Dot operator (.)
Used to access an object’s data members and member
functions.
Call this member function ( request one service from
this GradeBook object )
myGradeBook.displayMessage( );
objectName.memberFunction(para.);
23
Driver File
Driver files
Program used to test software (such as classes)
Contains a main function so it can be executed.
Example:
test.cpp (driver file)
#include “GradeBook.h” //include the definition
// of GradeBook class
int main()
{
GradeBook myGradeBook;
myGradeBook.displayMessage();
return 0;
}
24
Compilation and Linking Process
Compiles test.cpp, links GradeBook.o and makes
executable test.out
Command:
g++ test.cpp GradeBook.o –o test.out
Compiling class object code, compiling main function
object code, linking them to produce the executable file
with one command:
g++ test.cpp GradeBook.cpp –o test.out
25
Implementation File as the Driver File
main function could be put in the implementation file
(classA.cpp) to test classA.
#include “GradeBook.h”
void GradeBook::displayMessage()
{
}//end of member function
int main()
{
}//end of main function
Compiling command:
g++ GradeBook.cpp –o test.out
26
set Functions and get Functions
public member functions that allow clients of a class to
set or get the values of private data members.
set functions sometimes called mutators (setter) and get
functions sometimes called accessors (getter).
Allows the creator of the class to control how clients
access private data members.
Should also be used by other member functions of the
same class.
27
Set Functions
Set functions update the data members directly.
Example:
//in GradeBook.h
void setCourseNumber(int n);
//in GradeBook.cpp
void GradeBook::setCourseNumber(int n)
{
courseNumber = n;
}
Manipulate the object’s data, but which object’s data ?
Compiler passes the pointer to the object itself (this)
as an implicit argument to each member function.
The above statement is actually: this->courseNumber = 0;
28
Get Functions
Get the value of a data member.
Example:
//in GradeBook.h
int getCourseNumber( );
//in GradeBook.cpp
int GradeBook::getCourseNumber( )
{
return couresNumber;
}
29
Constructor
A special member function: to initialize an object of the
class when the object is created.
must have the same name as the class.
Never return any value (not even void).
Declared as public.
Usually the data members of the class are initialized inside
the constructor.
The constructor is called when an object of this class is
created.
30
Example
Class GradeBook’s constructor
//in GradeBook.h
GradeBook(int);
//in GradeBook.cpp
GradeBook::GradeBook(int n)
{
setCourseNumber(n);
}
//in test.cpp
GradeBook myGradeBook(2350);
31
Default Constructor
If you do not provide a constructor, the compiler
provides a default constructor for you – a constructor
with no parameters.
You can also provide a default constructor explicitly.
GradeBook::GradeBook()
{
setCourseNumber(1600);
}
32
Overloaded Constructors
Overloaded Functions: Functions having the same
name but different sets of parameters.
The parameter types
The number of parameters
The order of the parameter types
Overloaded Constructors: Constructors with different
sets of parameters.
33
Constructor with Arguments vs.
Default Constructor
If a constructor with parameters (arguments) is defined in
a class, C++ will not implicitly create a default
constructor for this class.
If you want to have a default constructor, explicitly define
it by yourself.
34
Destructors
A special member function
Name is the tilde character (~) followed by the class
name, e.g., ~GradeBook( )
Called implicitly when an object is destroyed
For example, this occurs as an automatic object is destroyed when
program execution leaves the scope in which that object was
instantiated
The destructor itself does not actually release the object’s
memory
It performs termination housekeeping
Then the system reclaims the object’s memory
35
So the memory may be reused to hold new objects
Destructors (Cont.)
Receives no parameters and returns no value
A class may have only one destructor
May not specify a return type—not even void
Destructor overloading is not allowed
If the programmer does not explicitly provide a
destructor, the compiler creates an “empty” destructor
36
When Constructors and Destructors
Are Called
Constructors and destructors are called implicitly by the
compiler
37
Order of these function calls depends on the order in which
execution enters and leaves the scopes where the objects are
instantiated
Exercise
Modify class GradeBook
38
To include a second string data member that represents the
course instructor’s name
Provide a set function to change instructor’s name, and a get
function to retrieve the instructor’s name
Modify the constructor to specify course name, instructor
name paremsters.
Modify function displayMessage to output the welcome
message and source name, then the string “This course is
presented by: “ followed by instructor’s name.
Modify the test program to demonstrate the class’s new
capabilities.
C++ Classes
A class defines a new data type
A class contains data members
and methods (member
functions)
By default, all members in a
class are private
But you can specify them as public
An object is an instance of a
class
Encapsulation hides
implementation details
39
C++ Scope Rule
Scope: the portion of the program where an identifier
(variable name, function) can be used
Block scope
Function scope
40
global variable, functions defined outside of a class are known from its
declaration to the end of file
Class scope
labels can be used in goto statement within the function it’s declared
File scope
Variables defined within a block is “known” from its declaration to the
“}”
Class member function or member data has a class scope
Namespace scope
Class Scope and Member Accessing
Class scope contains
Within a class’s scope
Data members: variables declared in class definition
Member functions: functions declared in class definition
Class members are accessible by all member functions
Outside a class’s scope
41
private class members could not be accessed
public class members are referenced through a handle
An object name, e.g., myGradeBook1.setCourseName(…)
A reference to an object
A pointer to an object,
dot member selection operator (.)
Hidden Class-Scope Variable
Variables declared in a member function
Have block scope, i.e., known only within that function
Local variable or parameter hide (eclipse) a class-scope
variable with same name:
void GradeBook::setCourseNumber(int courseNumber)
{
courseNumber = courseNumber;
}
the class-scope variable is hidden
To refer a hidden variable, precede its name with “this.”
void GradeBook::setCourseNumber(int courseNumber)
{
this.courseNumber = courseNumber;
}
42
Let’s trace the GradeBook
example…
43
Time class case study
44
Time Class Case Study
Time Class Definition:
private data members:
public member functions:
45
int hour;
int minute;
int second;
Time( ); //default constructor
Time(int, int, int); //constructor setting h., m., s.
void setTime(int, int, int); //set h., m., s.
void printUniversal();//print time in universal format
void printStandard(); //print time in standard format
Preprocessor Wrappers
Prevents code from being included more than once
#ifndef – “if not defined”
#define
Define a unique Name so this code will not be included again
#endif
If the header has been included previously
Skip this code if it has been included already
Name is defined already and the header file is not included
again
Prevents multiple-definition errors
46
// Fig. 9.1: Time.h
// Declaration of class Time.
// Member functions are defined in Time.cpp
1
2
3
4
5
6
7
8
9
10
// prevent multiple inclusions of header file
#ifndef TIME_H
Preprocessor directive
#define TIME_H
// Time class definition
class Time
#ifndef determines whether a name is defined
Preprocessor directive #define defines a name (e.g., TIME_H)
11 {
12 public:
13
Time(); // constructor
14
void setTime( int, int, int ); // set hour, minute and second
15
void printUniversal(); // print time in universal-time format
16
void printStandard(); // print time in standard-time format
17 private:
18
int hour; // 0 - 23 (24-hour clock format)
19
int minute; // 0 - 59
20
int second; // 0 - 59
21 }; // end class Time
22
23 #endif
Preprocessor
directive #endif marks the end of the
code that should not be included multiple times
47
Software Engineering Observation
Each element of a class should have private visibility
unless it can be proven that the element needs
public visibility.
48
Time Class Constructors
Default constructor
Overloaded constructor
Time ();
Every data member is initialized to zero.
Time(int, int, int);
data members of a class could not be initialized where they are
declared in the class body.
One constructor is called when the Time object is
created.
49
Time t1 ; //default constructor is called
Time t2 (1, 34, 20); //second constructor is called.
Time Class Member Functions
Set Functions
void setHour(int);
void setMinute(int);
void setSecond(int);
void Time::setHour(int h)//[0,24)
{
if (h>=0 && h<24)
hour = h;
else
hour = 0;
}
50
Formatting numeric output (1)
Stream manipulator setw(width)
51
Requires header file <iomanip>
Sets field width and applies only to the next output value
Example:
cout<< setw(12) << numberOne <<endl;
If numberOne is less than 12 character positions wide, the
output is Right justified by default and padded with fill
characters.
If numberOne is more than 12 character positions wide, the
field width is extended to accommodate the entire value.
Formatting numeric output (2)
Stream manipulator left to left-justify , <iostream>
Stream manipulator right to right-justify,
<iostream>
Stream manipulator setfill(c), <iomanip>
Example:
cout << setfill(‘x’) << left
<< setw(12) << numberOne << endl;
52
Time Class Member Functions
void printUniversal();
void Time::printUniversal()
{
cout<<setfill('0')
<< setw(2) << hour<<":"
<< setw(2) << minute <<":"
<< setw(2) << second;
}
53
Time Class Member Functions
void printStandard();
void Time::printStandard()
{
int sH = convertHour();
cout <<
<<
<<
<<
setfill('0')
setw(2) << sH <<":"
setw(2) << minute << ":"
setw(2) << second;
if (hour < 12) cout<<" AM";
else
cout<<" PM";
}
54
Using Class Time
Once class Time has been defined, it can be used in
declarations
Time sunset(18,5,0);
//object of type Time
Time arrayOfTimes[ 5 ];
//array of 5 Time objects
Time &dinnerTime = sunset;
//reference(alias) to a Time object
Time *timePtr = &dinnerTime;
//pointer to a Time object
55
Use Class Member Functions
Member function is within the class’s scope: known only
to other members of the class
Otherwise: use dot member selection operator (.)
56
An object (instance) of the class
sunset.printUniversal( );
Reference to an object of the class
dinnerTime.printStandard( );
Pointer to an object of the class
(*timePtr).printStandard( );
Arrow member selection operator (->) for pointer
timePtr -> printStandard( );
Category of member functions
Set function
Get function
Access function
Utility function
57
Access Functions
read or display data
test the truth or falsity of conditions
58
void printStandard( );
void printUniversal( );
Such functions are often called predicate functions
For example, isAM( ) function for Time Class.
Utility Functions (helper functions)
private member functions that support operation of
the class’s public member functions
Not part of a class’s public interface
59
Not intended to be used by clients of a class
Example: int convertHour();
Software Engineering Observation
Avoid repeating code:
60
If a member function of a class already provides all or part
of the functionality required by a constructor (or other
member function) of the class, call that member function
from the constructor (or other member function).
Simplifies code maintenance
Reduces the likelihood of an error if the
implementation of the code is modified.
Default Memberwise Assignment
Assignment operator (=)
Can be used to assign an object to another object of the same
type
Time t1(12,0,0);
Time t2;
t2=t1;
61
Each data member of t1 (the right-hand side object) is assigned to the
same data member in t2 (the left-hand object)
Caution: can cause serious problems when data members
contain pointers to dynamically allocated memory
Extending Time class
To provide a member function that calculate number of
seconds elapsed from a given time object (startingTime)
to the object itself (this)
int SecondPassedSince (Time & startingTime);
Ex:
Time time1(10,0,0);
// time the class starts
Time time2 (10,4,25);
// time you showed up
int secondsPassed = time2.SecondPassedSince(time1);
// secondsPassed should be the number of seconds
passed from time1 until time2,
62
/* return 0 if startingTime is sometime in the future than the
calling Time object */
int Time::SecondPassedSince (Time & startingTime){
int duration=0;
if (hour<startingTime.hour)
return 0;
else if (hour>startingTime.hour){
duration=(hour-startingTime.hour)*60*60;
}
duration+=(minute-startingTime.minute)*60;
duration+=(second-startingTime.second)*60;
if (duration<0)
return 0;
else
return duration;
}
63