ObjectOriented Programming - PowerPoint PPT Presentation

1 / 41
About This Presentation
Title:

ObjectOriented Programming

Description:

We have used classes for input/output, (istream & stream, ... 'Code Bloat' Functions in Header File. It is possible to implement functions in the h files. ... – PowerPoint PPT presentation

Number of Views:57
Avg rating:3.0/5.0
Slides: 42
Provided by: cstlcs
Category:

less

Transcript and Presenter's Notes

Title: ObjectOriented Programming


1
  • Object-Oriented Programming
  • Classes

2
Classes
  • In this chapter Object-oriented programming
  • We have used classes for input/output, (istream
    stream,ifstream,ofstream), strings and vectors.
    In this chapter, we will see how to create new
    classes.
  • We will consider a simple class, Time

3
What Is a Class?
  • Classes are extensions of the C-Style structs
  • They will contain data members but
  • They may also contain function members to perform
    operations on the data members.
  • It provides a way to implement ADTs with the
    storage for the data and the operations
    encapsulated in one structure.
  • Private (default) and Public parts

4
Classes Are Basis for OOP
  • Leads to a new style of programming, OOP
  • An object is a particular instance of a class or
    an instantiation of a class
  • Objects can be self contained, performing their
    own operations. Examples
  • cin is an object of the istream class, cout of
    the ostream class.
  • string s creates the object s as an instance of
    the string class

5
C Structs vs. C Classes ( Structs)("traditiona
l" vs "OOP")
C's structs and classes model objects that
have ? Attributes (characteristics) represented
as and
data members
? Operations (behaviors) represented as
(also called methods).
function members
Operations
This leads to a whole new style of programming
object-oriented. Objects are self-contained, poss
essing their own operations commonly called
the I can do it myself principle rather than
being passed as a parameter to an external
function that operates on them and sends them
back.
Function Members
Data Members
Attributes
6
Format of a Class
  • class classname
  • public
  • . . .
  • private
  • . . .

7
Private and Public
  • Data members are generally private
  • Member functions are generally public
  • Private members may be used only by member
    functions (and friend functions)
  • Public members may be used by both member and
    nonmember functions.
  • Member functions are accessed using the dot
    notation as in structs.

8
Header and Implementation Files
  • Class declarations are usually placed in a
    library which consists of a header file(.h) and
    and an implementation file(.cpp). This is not
    always done, template classes, like vectors, have
    to be in an h file.
  • The cpp file is used to contain the
    implementation of non-trivial member functions

9
Access to Class Members
A particular instance of a class is called an
object ClassName object_name Private members
can be accessed only within the class (object)
(except by friend functions to be described
later). Public members can be accessed within or
outside the class(object) to access them
outside the class (object), one must use the dot
operator object_name.public_member_name
A class declaration is usually placed in a header
file whose name is ClassName.h . The library is
then called a class library.
10
Example of Time Class
/ Time.h ---------------------------------------
----------------- This header file defines the
data type Time for processing time. Basic
operations are Set To set the time
Display To display the time -------------------
--------------------------------------------------
-/ include ltiostreamgtusing namespace
std class Time/ Member functions
/public / Set sets the data members of
a Time object to specified values.
Receive hours, the number of hours in standard
time minutes, the number of minutes
in standard time AMPM ('A' if AM,
'P' if PM) Postcondition The Time object
containing this function has its
myHours, myMinutes, and myAMorPM members set to
hours, minutes, and am_pm,
respectively, and myMilTime to the
equivalent military time
/
Plus Name, Course , Lab/Project , etc.
void Set(unsigned hours, unsigned minutes, char
am_pm)
11
/ Display displays time in standard and military
format using output stream out.
Receive ostream out Output The
time represented by the Time object containing
this function Passes back
The ostream out with time inserted into it

/
void Display(ostream out) const /
Data Members / private unsigned
myHours, myMinutes char
myAMorPM // 'A' or 'P' unsigned
myMilTime // military time equivalent //
end of class declaration
Notes 1. "my" in data members names is a
reminder of internal ("I can do it myself")
perspective. 2. const at end of Display()'s
prototype makes it a const functionwhich means
it cannot modify any of the data members. Good
idea to protect data members from accidental
modification.
"Accessors"vs. "Mutators"
12
3. Why make data members private? "Hidden" data
members ? Cannot be accessed outside class ?
Application programs must interact with an object
through its interface? Public member functions
control interaction between programs and class.
? Application programs need not know about
implementation! ? Implementation may change
(improve storage, simpler algorithms. etc.) ? If
interface is constant, programs using an object
need not be changed. ? Always define data
members of a class as private.
13
Access Functions to Get and Set Private Data
  • Should make data private, accessible only through
    access functions.
  • get functions return private values, e.g.
  • unsigned GetHour() const return myHours
  • char GetAMPM() const return myAMorPM
  • set functions change values of private
    variables
  • unsigned SetHours(int theHours) myHours
    theHours
  • char GetAMPM(char AorP) myAMorPM AorP

14
Implementation of a Class
Class declaration contains ? Declarations of
data members ? Prototypes (declarations) of
function members Definitions of function
members are not usually placed in class
declaration ? Avoid cluttering up the interface
Definitions placed outside the class
declaration must tell compiler where the
corresponding declaration/prototype is Use
the scope operator which has the
form ClassNameItemName (the qualified or
full name of ItemName.)
This applies also to constants and types declared
within a class.
e.g., Lab 3
15
Implementation of Member Functions
  • The implementation of member functions normally
    would appear in the cpp file, for example
  • void TimeSet(unsigned hours, unsigned minutes,
    char am_pm)
  • assert(hours gt 1 hours lt12
  • minutes lt 59 minutes gt 0
  • (am_pm 'P' am_pm 'A'))
  • myHours hours
  • myMinutes minutes
  • myAMorPM am_pm
  • myMilTime 100myHours myMinutes
    (myAMorPM 'P'? 12000)

16
Notes
1. Member functions "Inside" an object, so
don't pass object to them as a parameter. (They
receive the object to be operated on implicitly,
rather than explicitly via a parameter.)Non-memb
er functions "Outside" an object, so to operate
on an object, they must receive it via a
parameter. 2. Public items must be qualified when
referred to outside the class declaration Class
NameItemNamePublic constants are usually
declared static so they are global class
properties that can be accessed by all objects
of that class type rather than each object having
its own copy. 3. Simple member functions
Usually specified as inline functions. This
suggests to compiler to replace a function call
with actual code of the function with parameters
replaced by arguments saves overhead of
function call.
Danger"Code Bloat"
17
Functions in Header File
  • It is possible to implement functions in the h
    files. This is often done if their implementation
    is simple and we want them to be inline
    functions. Calls to inline functions are replaced
    by the compiler with the actual code, avoiding
    the overhead of the function call.
  • Two ways to do this

18
Inline Function Implemented Inside Class
Declaration
  • class Time
  • public
  • void Display(ostream out) const
  • out ltlt myHours ltlt '' ltlt
  • (myMinutes lt10? "0""") ltlt myMinutes
  • ltlt " " ltlt myAMorPM ltlt".M. ("
  • ltlt myMilTime ltlt " Mil Time)\n"
  • void Set(unsigned hours, unsigned minutes,
    char am_pm) . . . // end of
    class declaration

19
Inline Function ImplementedAfter Class
Declaration
  • Must use inline keyword
  • class Time
  • public void Display(ostream out) const .
    . .
  • //end of class
  • inline void TimeDisplay(ostream out) const
  • out ltlt myHours ltlt '' ltlt
  • (myMinutes lt10? "0""") ltlt myMinutes
  • ltlt " " ltlt myAMorPM ltlt".M. ("
  • ltlt myMilTime ltlt " Mil Time)\n"

20
Class Constructors
  • Constructor allocates memory and initializes the
    object. Compiler provides a default constructor
    but others may be added. If another is added
    then default one must be written.
  • Constructors are named same as class name.
  • Public member functions
  • No return type
  • Automatically called when object is declared

21
Default Constructor(no parameters uses default
values)
  • Implementaton in Class declaration
  • Time()
  • myHours 12
  • myMinutes 0
  • myAMorPM A
  • myMilTime 0
  • Called by declaration Time now

22
Explicit-Value Constructor(Initial values passed
as arguments.)
  • Time(unsigned initHours, unsigned initMinutes,
    char initAMPM)
  • // use assert to verify correctness of
    parameters
  • myHoursinitHours
  • myMinutesinitMinutes
  • myAMorPMinitAMPM
  • myMilTime100myHoursmyMinutes
  • (myAMorPM'P'?12000)
  • Call Time now (2, 45 , P)

23
Combination Constructorwith Default
Arguments(replaces default and explicit)
  • Time(unsigned initHours 12, unsigned
    initMinutes 0,
  • char initAMPM 'A')
  • myHours initHours
  • myMinutes initMinutes
  • myAMorPM initAMPM
  • myMilTime 100myHoursmyMinutes
  • (myAMorPM'P'?12000)
  • Can be called with or without arguments Time
    t, now(10), later(11,45), ex(11, 34,P)
  • After t is defined, could do either of the
    following
  • Time new t or Time new(t)

24
Testing 1 Time mealTime, //default
constructor bedTime(11,30,'P')
//explicit-value constructor Create and
initialize 2 Time objects
Time()
Time(11,30,'P')
12
11
0
30
A
P
0
2330
mealTime.Display(cout) cout ltlt
endlbedTime.Display(cout) cout ltlt endl
Execution 1200 A.M. (0 mil. time) 1130 P.M.
(2330 mil. time)
25
Testing Time mealTime, t1(5), t2(5, 30), t3(5,
30, 'P') Creates 4 Time objects
Execution 1200 A.M. (0 mil. time)500 A.M.
(500 mil. time)530 A.M. (530 mil. time)530
P.M. (1730 mil. time)
mealTime.Display(cout) cout ltlt
endlt1.Display(cout) cout ltlt
endlt2.Display(cout) cout ltlt
endlt3.Display(cout) cout ltlt endl
26
Copy Operations
Two default copy operations are provided 1.
Copy in initialization (via
) 2. Copy in assignment (via
)
copy constructor
assignment operator
Each makes a raw (bitwise) copy of the memory
allocated to the data members of the object.
27
Examples Time t bedTime Time
t(bedTime) Both 1. Allocate memory for
t 2. Copy data members of bedTime so t is a copy
of bedTime
In contrast Time t Time(11, 30, 'P') calls
the explicit-value constructor to construct a
(temporary) Time object and then copies it into t.
Note These are not assignments a default copy
constructor is called.
28
There is a default copy operation for assignment.
Example t mealTime copies the members of
mealTime into t, replacing any previous values
12
12
0
0
A
A
0
0
29
Overloaded Operators(Operators with same name,
different parameter types)
  • In C, it is possible to overload operators such
    as ltlt , gtgt , lt , etc.
  • Examples
  • if the ltlt operator is overloaded for the class
    Time, then we can write Time now
    (11,34,P) cout ltlt now
  • if the lt operator is overloaded for Time, can
    write Time now (11, 34, P), then
    (11, 55, A) if (then lt now) . . .

30
Overloaded Operators AreExecuted As Functions
  • Overloaded OP is treated by the system as the
    function operator OP( ). Examples
  • If ltlt is overloaded as a non-member function,
    then cout ltlt now is interpreted as a
    function call operatorltlt (cout,
    now)
  • If lt is overloaded as a member function,then
    (now lt then) interpreted as
    now.operatorlt(then)

31
Overloading lt for Time
  • Declare as a public member function.
  • May be implemented as inline, inside class
    declaration
  • bool operatorlt (const Time t)
  • return myMilTime lt
  • t.myMilTime
  • If implemented outside of class declaration,
    dont forget scope operator, bool
    Timeoperatorlt (const Time t)

32
Overloading input/output Operators for Time
  • Input (gtgt) and output (ltlt) operators are iostream
    member functions, not member functions of Time
  • Two ways to implement them
  • outside of class declaration must call a
    public function (like Display)
  • inside class declaration as a friend function

33
Overloading ltlt for a Class
Method 1 Put definition in .h file, after class
declaration, and have it call a public
output function member. Inline it,
because it's simple.
inline ostream operatorltlt(ostream out, const
Time t)
t.Display(out) return out
Note No Time It's not a member function!
34
Method 2 Define operatorltlt()outside the class
declaration as a non-member function and (i)
use accessors to display data members, or (ii)
declare it to be a friend in the class
declaration.
In class declaration / doc. as before /friend
ostream operatorltlt(ostream out, const Time
t) Outside class declaration (in .cpp
file) ostream operatorltlt(ostream out, const
Time t) out ltlt t.myHours ltlt '' ltlt
(t.myMinutes lt 10 ? "0" "") ltlt
t.myMinutes ltlt ' ' ltlt t.myAMorPM ltlt ".M.
(" ltlt t.myMilTime ltlt " mil. time)"
return out
35
Friend Functions
  • A class may name a function as a friend
  • a friend is not a member function, but explicitly
    receives object as parameter
  • it has access to private data which it
    references as parameter.data

36
Overloading ltlt for Time, As a Friend Function
  • In public part of class declaration
  • friend ostream operatorltlt(ostream out,
    const Time t)
  • out ltlt t.myHours ltlt '' ltlt t.myMinutes
  • ltlt
    (t.myAMorPM 'A'?'A''P')
  • ltlt ".M. (mil time "
  • ltlt t.myMilTime ltlt " )\n"
  • return out

37
Things to Note About Overloaded ltlt Function
  • Both the ostream and the Time objects are passed
    as arguments (ltlt is not a member function of
    time)
  • The data members of the Time object can be
    accessed directly because ltlt is a friend
    function.
  • The return type is ostream and the object out is
    returned, so that calls can be chained, e.g.
    cout ltlt now ltlt , ltlt then

38
Preventing Redundant Declarations
  • If include classname.h directives occur more
    than once in the same file (may be in another
    file which is included) can cause redeclaration
    error.
  • Avoid this with conditional compilation
  • at top of .h file
  • ifndef some unique name (not the class
    name) define same unique name
  • at end of .h file endif
  • A standard name to use is class name in caps
    TIME

39
String ADT
  • One possible implementation with a Strings class,
    using
  • C-Style array of chars to hold data
  • End of string represented by \0 character.
  • length() and empty() functions look for \0
    character. (Length not stored.)

40
C String Class
  • some member functions
  • constructors string(...)
  • overloaded gtgt and ltlt operators(Note use
    getline(cin, s) to read entire line.)
  • overloaded operator
  • insert, erase, find, etc.
  • may be converted to a String Stream

41
String Streams
  • defined in ltsstreamgt library
  • member functions gtgt and ltlt (e.g., can read
    from the string, similar to cin)
  • explicit value constructor for input string
    stream istringstream name (string s)
  • examplestring name, phone istringstream istr
    (Adams 651-2456)istr gtgt name gtgt phone
  • member function istr.str(s) sets istr to the
    value of s converted to a stringstream.
Write a Comment
User Comments (0)
About PowerShow.com