Title: Classes 2
1Classes (2)
- CSC 2110 - Data Structures Abstraction
- Spring/Summer 2001
- Wayne State University
- Instructor Anne-Marie Bosneag
2Content
- Records vs. classes
- Inheritance
- Composition
- Static dynamic binding
- Virtual functions
- Class invariants
- Exceptions
- Namespace
3Comparison of struct and class
- Members in structs are public by default, which
provides more flexible and convenient access - Members in classes are private by default, which
requires public member functions to access.
Better information hiding and security
4Example struct
- struct StudentType
- char name50
- int age
- char gender //M or F
-
- StudentType student1
- strcpy(student1.name, John R. Smith)
- student1.age30
- student1.genderM
- cout ltlt student1.name
- cout ltlt student1.age
- cout ltlt student1.gender
- void out_put(StudentType student)
- cout ltlt Name is ltlt student.name ltltendl
- cout ltlt Gender is ltlt student.gender ltlt
endl - cout ltlt Age is ltlt student.age ltltendl
- //the name may cause ambiguity
- //if there is another struct that
- //needs the output function
- void output(PersonType person)
- output(student1)
5Example class
- StudentType student1
- strcpy(student1.name, John R. Smith) //not
allowed - void StudentType set_name(char str50)
- strcpy(name, str)
-
- student1.set_name(John R. Smith)
-
- cout ltlt student1.age//not allowed
- int StudentTypeget_age()
- return age
-
- cout ltlt student1.get_age()
- class StudentType
- public
- void set_name(char str50)
- void set_age(int num)
- void set_gender(char g)
- char get_name()
- int get_age()
- int get_gender()
- void out_put()
- private
- char name50
- int age
- char gender
6Example class
- void StudentTypeoutput()
- cout ltlt Name is ltlt student.name ltltendl
- //the above statement //constains an error
- cout ltlt Gender is ltlt gender ltlt endl
- cout ltlt Age is ltlt
- age ltltendl
-
- student1.output()
- Notes
- in classes, all data and related operations are
encapsulated together - in structs, data and functions are two separate
part - therefore classes are easier to reuse
- classes are more suitable in developing large
programs
7Two Programing Paradigms
Structural (Procedural) Object-Oriented
PROGRAM PROGRAM
8Object-Oriented Programming Language Features
- 1. Data abstraction
- 2. Inheritance of properties
-
- 3. Dynamic binding of operations to objects
-
9Object oriented terms
OOP Terms C Equivalents
Object Class object or class instance Inst
ance variable Private data member Method Publi
c member function Message passing Function call
( to a public member function )
10What is an object?
OBJECT
set of methods (public member functions) interna
l state (values of private data members)
Operations Data
11Inheritance hierarchy among vehicles
Every car is a wheeled vehicle.
12Inheritance
- is a mechanism by which one class acquires
(inherits) the properties (both data and
operations) of another class. - The class being inherited from is the Base Class
(Parent). - The class that inherits is the Derived Class
(Child). - The derived class is then specialized by adding
properties specific to it.
13Example
- // SPECIFICATION FILE ( time.h )
- class TimeType
- public
- void Set ( int hours , int minutes ,
int seconds ) - void Increment ( )
- void Write ( ) const
- Time ( int initHrs, int initMins, int
initSecs ) - Time ( )
- private
- int hrs
- int mins
- int secs
-
14Class interface diagram
Time class
15Using inheritance to add features
- // SPECIFICATION FILE ( exttime.h)
- include time.h
- enum ZoneType EST, CST, MST, PST, EDT, CDT,
MDT, PDT - class ExtTime public Time // Time is
the base class - public
- void Set ( int hours, int minutes,
int seconds , -
ZoneType timeZone ) - void Write ( ) const
- ExtTime ( int initHrs , int initMins ,
int initSecs , - ZoneType initZone ) //
constructor - ExtTime ( ) // default constructor
- private
- ZoneType zone // added data member
-
16class ExtTime public Time
- says class Time is a public base class of the
derived class ExtTime. - As a result, all public members of Time (except
constructors) are also public members of ExtTime. - In this example, new constructors are provided,
new data member zone is added, and member
functions Set and Write are overridden.
17 Class Interface Diagram
ExtTime class
Private data hrs mins secs
Privatedata zone
18Client Code Using ExtTime
- include exttime.h
- .
- .
- ExtTime thisTime ( 8, 35, 0, PST )
- ExtTime thatTime // default
constructor called - thatTime.Write( ) // outputs
000000 EST - cout ltlt endl
- thatTime.Set (16, 49, 23, CDT)
- thatTime.Write( ) // outputs
164923 CDT - cout ltlt endl
- thisTime.Increment ( )
- thisTime.Increment ( )
- thisTime.Write ( ) // outputs
083502 PST - cout ltlt endl
19Constructor Rules for Derived Classes
- At run time, the base class constructor is
implicitly called first, before the body of the
derived classs constructor executes. - If the base class constructor requires
parameters, they must be passed by the derived
classs constructor.
20Implementation of ExtTime Default Constructor
- ExtTime ExtTime ( )
- // Default Constructor
- // Postcondition
- // hrs 0 mins 0 secs
0 - // (via implicit call to base class
default constructor) - // zone EST
-
- zone EST
21Implementation of Another ExtTime Class
Constructor
- ExtTime ExtTime ( / in / int
initHrs, - / in / int
initMins, - / in / int
initSecs, - / in /
ZoneType initZone ) - Time (initHrs, initMins, initSecs)
// constructor initializer - // Precondition 0 lt initHrs lt 23 0
lt initMins lt 59 - // 0 lt initSecs lt 59 initZone is
assigned - // Postcondition
- // zone initZone Time set by base class
constructor - zone initZone
22Implementation of ExtTime Set function
- void ExtTime Set ( / in / int
hours, - / in / int
minutes, - / in / int
seconds, - / in /
ZoneType time Zone ) - // Precondition 0 lt hours lt 23 0 lt
minutes lt 59 - // 0 lt seconds lt 59 timeZone is
assigned - // Postcondition
- // zone timeZone Time set by base class
function -
- Time Set (hours, minutes,
seconds) - zone timeZone
23Implementation ExtTime Write function
- void ExtTime Write ( ) const
- // Postcondition
- // Time has been output in form HHMMSS ZZZ
- // where ZZZ is the time zone
abbreviation -
- static char zoneString84
- EST, CST, MST, PST, EDT, CDT, MDT,
PDT -
- Time Write ( )
- cout ltlt ltlt zoneString zone
-
24Composition (containment)
- is a mechanism by which the internal data (the
state) of one class includes an object of another
class.
25Example
- A TimeCard object has a Time object
- include time.h
- class TimeCard
- public
- void Punch ( / in / int hours,
/ in / int minutes, - / in /
int seconds ) - void Print ( ) const
- TimeCard ( / in / long idNum, /
in / int initHrs, - / in / int initMins,
/ in / int initSecs ) - TimeCard ( )
- private
- long id
- Time timeStamp
-
26 Class Interface Diagram
TimeCard class
Private data id timeStamp
Print . .
Private data hrs mins secs
Write . . .
TimeCard
TimeCard
27Implementation of TimeCard Class Constructor
- TimeCard TimeCard ( / in / long idNum,
- / in / int initHrs,
- / in / int initMins,
- / in /
int initSecs ) - timeStamp (initHrs, initMins, initSecs)
// constructor initializer - // Precondition 0 lt initHrs lt 23 0
lt initMins lt 59 - // 0 lt initSecs lt 59 initNum is
assigned - // Postcondition
- // id idNum timeStamp set by its
constructor - id idNum
28Order in which constructors are executed
- Given a class X,
- If X is a derived class its base class
constructor is executed first. - Next, constructors for member objects (if any)
are executed (using their own default
constructors if none is specified). - Finally, the body of Xs constructor is executed.
29In C . . .
- When the type of a formal parameter is a
- parent class, the actual parameter can be
- the same type as the formal parameter,
- or,
- any descendant class type.
30Static Binding
- is the compile-time determination of which
function to call for a particular object based on
the type of the formal parameter. - When pass-by-value is used, static binding occurs.
31Static Binding Is Based on Formal Parameter Type
- void Print ( / in / Time someTime )
-
- cout ltlt Time is
- someTime.Write ( )
- cout ltlt endl
-
- CLIENT CODE OUTPUT
- Time startTime ( 8, 30, 0 ) Time is
083000 - ExtTime endTime (10, 45, 0, CST) Time is
104500 - Print ( startTime )
- Print ( endTime )
32Dynamic Binding
- is the run-time determination of which function
to call for a particular object of a descendant
class based on the type of the actual parameter. - declaring a member function to be virtual
instructs the compiler to generate code that
guarantees dynamic binding.
33Virtual Member Function
- // SPECIFICATION FILE ( time.h )
- class TimeType
-
- public
- . . .
- virtual void Write ( ) const
// for dynamic binding - . . .
- private
- int hrs
- int mins
- int secs
-
34Dynamic binding requires pass-by-reference
- void Print ( / in / Time someTime )
-
- cout ltlt Time is
- someTime.Write ( )
- cout ltlt endl
-
- CLIENT CODE OUTPUT
- Time startTime ( 8, 30, 0 ) Time
is 083000 - ExtTime endTime (10, 45, 0, CST) Time
is 104500CST - Print ( startTime )
- Print ( endTime )
35Using virtual functions in C
- Dynamic binding requires pass-by-reference when
passing a class object to a function. - In the declaration for a virtual function, the
word virtual appears only in the base class. - If a base class declares a virtual function, it
must implement that function, even if the body is
empty. - A derived class is not required to re-implement a
virtual function. If it does not, the base class
version is used.
36Class invariants
- the relationship that should always hold for the
class (denoted CLASSINV by convention) - ex. for the container class, numunits gt 0
- all member functions (except the constructor)
assume the invariant is true at invocation - it is the constructors responsibility to
initialize the invariant to be true - all member functions (including the constructor)
must ensure the invariant is still true at return
37 Exceptions
- An exception is an unusual situation that occurs
when the program is running. - Exception Management
- Define the error condition
- Enclose code containing possible error (try).
- Alert the system if error occurs (throw).
- Handle error if it is thrown (catch).
38 try, catch, and throw
- Try
-
- // code that contains a possible error
- throw string(An error has occurred in
function ) -
- Catch (string message)
-
- stdcout ltlt message ltlt stdendl
- return 1
39Namespace
- namespace mySpace
-
- // All variables and functions within this
- // block must be accessed using scope
- // resolution operator ().
-
- Purpose Avoid namespace pollution.
40 3 Ways to Access Members within a Namespace
- Qualify each reference
- mySpacename with every reference.
- Using declaration
- using mySpacename
- All future references to name refer to
mySpacename. - Using directive
- using namespace mySpace
- All members of mySpace can be referenced without
qualification.
41Rules for Use of Namespace std (within text)
- Qualify names in prototypes and/or function
definitions. - If name used more than once in a function block,
use a using declaration. - If more than one name is used from a namespace,
use a using directive.