Title: Data Abstraction Through Classes
1Data Abstraction Through Classes
- CSC 2110 - Data Structures Abstraction
- Spring/Summer 2001
- Wayne State University
- Instructor Anne-Marie Bosneag
2Content
- Definition of classes
- Private public members
- Instantiation of the class type
- Specification, implementation, client modules
- Constructor destructor
- Member functions operators
- Records vs. classes
3Introduction
- An Algorithm contains two elements
- Data Information represented in different types
and manipulated by the algorithm - Control flow the order in which the instructions
are executed - Data abstraction
- data-centered programming where control plays a
supporting role - hide details
- reduce complexity
4Abstract Data types
- Each built-in data type has two characteristics
- a set of values
- allowable operations
- Example int, char, float
- To design an abstract data type
- data representation with existing data types
- implement allowable operations
5Object-Oriented Design
A technique for developing a program in which the
solution is expressed in terms of objects --
self- contained entities composed of data and
operations on that data.
ltlt
gtgt
setf
get
Private data
Private data
. . .
. . .
ignore
cout
cin
6 Familiar Class Instances and Member
Functions
- The member selection operator ( . ) selects
either data members or member functions. - Header files iostream and fstream declare the
istream, ostream,and ifstream, ofstream I/O
classes. - Both cin and cout are class objects and get is a
member function cin.get (someChar) -
- The following statements declare myInfile as an
instance of class ifstream and invoke member
function open. - ifstream myInfile
- myInfile.open ( A\\mydata.dat )
7 C class data type
- A class is an unstructured type that encapsulates
a fixed number of data components (data members)
with the functions (member functions) that
manipulate them.
8 class DateType Specification
- // SPECIFICATION FILE ( datetype.h )
- class DateType // declares a class data type
-
- public // 4 public member functions
- void Initialize ( int newMonth , int
newDay , int newYear ) - int YearIs( ) const //
returns year - int MonthIs( ) const //
returns month - int DayIs( ) const //
returns day - private // 3 private data members
- int year
- int month
- int day
-
8
9Class declaration
- The class declaration creates a data type and
names the members of the class. - It does not allocate memory for any variables of
that type! - Client code still needs to declare class
variables.
10Public and private components
- Public components
- define the interface of the class
- provide a collection of operations
- can be accessed directly by external operations
- Private components
- hidden from the client (but not the programmer)
- can not be accessed directly from outside
- only accessible to operations within the same
class
11Classes in C
- A programmer-defined type
- Components are called class members
- can be variables or functions
- Example in DatType class
- private members variables year, month, day
- public members functions YearIs, MonthIs, DayIs
and Initialize
12Classes in C
- Class declarations must end in semicolons
- Class members are private by default
- note that in struct members are public by default
- const keyword indicates that the function only
inspects but does not modify the private
variables - prevent the value from being modified by mistake
13Class as a type
- Once a class is defined, it can be used as a type
to declared instances - also called create objects an object is an
instance of a class - example
- DateType startDate, endDate//declare 2
//objects of //class DataType
14 Use of C data type class
- Variables of a class type are called objects (or
instances) of that particular class. - Software that declares and uses objects of the
class is called a client. - Client code uses public member functions (called
methods in OOP) to handle its class objects. - Sending a message means calling a public member
function.
15Operations on Classes
- Built-in operations valid on class objects are
- member selection using dot ( . ) operator ,
- assignment to another class variable using (
), -
- pass to a function as parameter
- (by value or by reference),
- return as value of a function.
- Other operations can be defined as class member
functions.
16Examples
- DateType Date1, Date2
- Date1.day3 //not allowed!
- //day can be accessed only //through the
public member //functions - Date1.YearIs()
- Date1.Initialize(5, 24, 2001)
- Date2Date1//aggregate assignment
- //the left and right side of must be of
the //same type
17Class scope
- The name of a class member is local to the class
- If the same name if declared for a variable
outside the class, they are unrelated - Example
- class JarType
- //public and private members
-
- int numUnits
- JarType jar1
- There is no ambiguity between numUnits and
jar1.numUnits
18Information hiding through classes
- Restrict the access of the client to the internal
data of classes - Decide which components should be public and
private - Typical pattern
- data are made private
- public part provides functions manipulating the
data
19Information hiding
- Private members can not be accessed directly by
dot notation - coutltltDate1.day//prohibited
- To access them, corresponding functions need to
be provided - cout ltlt jar1.DayIs()//allowed
- hide (and protect) private data from the client
20Specification and implementation
- Specification describes the behavior of the data
type - through class declaration
- presents the public interface in the form of
function prototypes - Implementation creates an abstraction barrier by
hiding the concrete data representation and code
for functions
21 2 separate files generally used for class
type
- // SPECIFICATION FILE (
datetype .h ) - // Specifies the data and function members.
- class DateType
-
- public
- . . .
- private
- . . .
-
- // IMPLEMENTATION FILE (
datetype.cpp ) - // Implements the DateType member functions.
-
- . . .
22 Implementation of DateType member functions
- // IMPLEMENTATION FILE
(datetype.cpp) - include datetype.h // also must appear
in client code - void DateType Initialize ( int newMonth, int
newDay, -
int newYear ) - // Post year is set to newYear.
- // month is set to newMonth.
- // day is set to newDay.
-
- year newYear
- month newMonth
- day newDay
22
23Implementation of DateType member functions
int DateType MonthIs ( ) const // Accessor
function for data member month return
month int DateType YearIs ( ) const //
Accessor function for data member year return
year int DateType DayIs ( ) const //
Accessor function for data member day return
day
24Implementation issues
- Contain the definitions (bodies) of the member
functions - Class name and scope resolution operator ()
must prefix the name of the member function - eliminate ambiguity
- Members of a class reference each other without
using the dot operator - Use const keyword to when the function does not
intend to modify any member
25 Client Code Using DateType
- include datetype // includes
specification of the class - include bool
- int main ( void )
-
- DateType startDate // declares 2
objects of DateType - DateType endDate
- bool retired false
- startDate.Initialize ( 6, 30, 1998 )
- endDate.Initialize ( 10, 31, 2002 )
- cout ltlt startDate.MonthIs( ) ltlt / ltlt
startDate.DayIs( ) - ltlt / ltlt startDate.YearIs( ) ltlt
endl - while ( ! retired )
- finishSomeTask( )
- . . .
-
-
25
26 DateType Class Instance Diagrams
startDate endDate
Private data year month day
1998 6 30
27Member functions
- A class member function operates on a class
instance (object), not on a class!! - Example
- DateType Date1
- Date1.Initialize(5, 24, 2001) //initializes
- only Date1, not all instances of the class
28Constructors
- A class constructor is a member function whose
purpose is to initialize the private data members
of a class object. - The name of a constructor is always the name of
the class, and there is no return type for the
constructor. - A class may have several constructors with
different parameter lists. A constructor with no
parameters is the default constructor. - A constructor is implicitly invoked when a class
object is declared. If there are parameters,
their values are listed in parentheses in the
declaration.
29Specification of constructors
- // SPECIFICATION FILE ( datetype.h )
- class DateType // declares a class data type
-
- public
- DateType() //default constructor
- DateType (int m, int d, int y) //parameterized
constructor - void Initialize ( int newMonth , int
newDay , int newYear ) - int YearIs( ) const //
returns year - int MonthIs( ) const //
returns month - int DayIs( ) const //
returns day - private // 3 private data members
- int year
- int month
- int day
-
30Implementation of constructor DateType()
- DateType()
-
- month 1
- day 1
- year 1900
31Implementation of constructor DateType(m, d, y)
- DateType (int m, int d, int y)
-
- month m
- day d
- year y
32Automatic invocation of constructors
- DateType Date1 // default constructor
invoked - DateType Date2 ( 5, 24, 2001 ) //
parameterized constructor - Date1 Date2
Private data year 1900 month 1 day 1
33More complex structures
- Arrays of class objects
- Structs as members of a class
- Another class instance as member of a class
34Array of class objects
- const int MAX_SIZE 50
- // declare array of class objects
- DateType Date MAX_SIZE
- The default constructor, if there is any
constructor, is invoked for each element of the
array.
35Example of a class having another class instance
as member
- class JarType
- public
- void Add (int n)
- int Quantity() const
- JarType(int n) //constructor
- JarType() //constructor
- private
- int numUnits
36Example (cont.)
- class NewType
- public
- void Func(int n)
- ...
- NewType(int jarunits) //constructor
- private
- float privateFloat
- JarType privateJar
-
37Example - implementation
- void NewTypeFunc (int n)
- privateJar.Add(n)
- if (privateJar.Quantity() gt 50)
- privateFloat3.4float(n)
-
- When a NewType instance is created, its
private Jar member also must be created. - NewTypeNewType(int jarUnits)privateJar(jarUnits
) - privateFloat 0.0
-
Constructor initializer list
38Constructors
- Suppose a class has two or more class
instances as members - class MyClass
- public
- ...
- MyClass(int n)
- private
- int privateVal
- YourClass alpha
- TheirClass beta
-
39Constructor initializor list
- MyClass MyClass (int n) alpha (n) ,
beta(n5) - privateVal n
- After the right paranthesis of the formal
parameter list, the colon marks the beginning
of the constructor initializer list. - Because alpha, a member of the MyClass class, is
an instance of the YourClass class, the parameter
n must be passed to the YourClass constructor.
40Constructor initializor list
- Therefore, YourClass is constructed before the
body of the MyClass constructor is executed. - The order of constructor calls (YourClass,
TheirClass) does not matter - The constructors are executed the order in which
they appear in the declaration of MyClass
41Friends
- Operations on abstract data types often require
two class instances as operands, such as equal
(or ) operand - Can be done in two ways
- As a member function of a class
- As a friend of a class
42An Equal Function as a Member of Class JarType
- Specification
- class JarType
- public
- Boolean Equal (JarType otherJar) const
- // where Boolean is typedef int Boolean
- ...
- private
- int numUnits
43Function Equal (cont)
- Client code
- JarType jar1
- JarType jar2
- ...
- if (jar1.Equal(jar2))
- ...
- Implementation
- Boolean JarTypeEqual(JarType otherjar) const
- return (numUnitsotherJar.Quantity())
44An Equal Function as a Friend of Class JarType
- Client code
- if (Equal (jar1,jar2))
- ...
- Specification
- class JarType
- public
- friend Boolean Equal (JarType firstjar,
- JarType secondjar)
- private
- int numUnits
- //Note Equal is not a member of the class
45Function Equal as Friend
- Implementation
- Boolean Equal (JarType firstjar,
- JarType secondjar)
- return (firstjar.Quantity()secondjar.Quantity()
)
46Operators
-
- Simply give a member (or friend) function the
following name - operatorltsymbolgt
- Example
- operator
47Specification of JarType, overloading the
operator
- class JarType
- public
- Boolean operator(jarType otherJar) const
- ...
- private
- int numUnits
48Operator overloading (cont)
- Implementation of operator function
- identical to Equal, but change name to operator
- Client can use either functional notation
- if (jar1.operator(jar2))
- ...
- or operator notation
- if (jar1jar2)
- ...
49Classes vs. Structs
- classes and structs
- data are private in classes by default while
public in structs - external operations can manipulate data in
structs directly - in classes, the access is much more restricted,
where private data can only be manipulated
through internal member functions
50Classes vs. Structs
- Structs - everyone has access to data
- advantage flexibility and convenience
- disadvantage risk of messing up
- Classes - access to data is controlled by member
functions - advantage security, detail-hiding
- disadvantage restricted access, more efforts
51Classes vs. Structs
- In developing small programs, using structs is
more convenient - The advantage of classes is illustrated in the
development and maintenance of large projects - Comprehensibility
- Security
- Reusability