Upload
branden-tate
View
234
Download
0
Tags:
Embed Size (px)
Citation preview
1
Classes and Data Abstraction
2
Objectives
• Understand encapsulation and data hiding
• Understand data abstraction and Abstract Data Types (ADTs)
• Create and use C++ ADTs (classes)
3
Introduction
• Object Oriented Programming (OOP) encapsulates– Data– Functions
• The data and functions are intimately tied together
• Classes "hide information"– implementation details hid to "outside
world"
Into packages called classes
4
Introduction
• Procedural languages (Pascal, C) tend to be action oriented– unit of programming is function or procedure
• OOP languages tend to be object oriented– unit of programming is the class– class objects are instantiated (an instance is
created)
• Classes are an evolution of the C notion of struct
5
Structure Definitions
• Structure an aggregate data type built using elements of other types
• Example:
• This gives us a new type– no space reserved in memory (yet)
– used to declare instances of variables (that is when space in memory is used)
struct Time { int hour; int minute; int second;};
6
Accessing Members of Structures
• Use member access operators– dot operator for instance name– arrow operator -> for pointers
struct Time { int hour; int minute; int second;};Time now, *t_ptr = &now;
cin >> now.minute;cout << t_ptr->minute; // (*t_ptr).minute
7
User Defined Type With a Struct
• Note sample program, figure 6.1, pg 367,8
• Structures usually passed by value– possible to avoid time and memory overhead by
using reference parameters (or pointers)
• When using reference parameters with struct, protect actual parameter by use of const parameter void do_stuff (const Time &tea_time);
8User Defined Type With a StructProblems ...
• Initialization not specifically required– possible to have uninitialized data– or invalid values assigned
• Any line in the program can assign potentially bad data to the struct
• Suppose implementation of struct Time is changed– all programs using the struct must be changed– no standardized interface exists
9
Solution
• Use
class
• Takes care of initialization
• Implementation is – locally done– separate from usage
• Interface remains standardized
10
User Defined Type With a Class
• Classes enable modeling objects that have– attributes (data members)– behaviors or operations (member functions)
• Class must be defined– then class name used to declare objects of that
class
11
User Defined Type With a Class
• Consider the following class definition and use of the class as a type
class Time { public: Time(); void setTime( int, int, int ); void printMilitary(); void printStandard(); private: int hour; // 0 - 23 int minute; // 0 - 59 int second; // 0 - 59 };. . .Time sunrise, time_list[5], *time_ptr;
WarningDon't forget the semicolon
12
User Defined Type With a Class
• Note the declarations of public: and private:– Public => any instance of the class can call
these functions– Private => only functions inside the class can
access these objects
• Examples sunrise.setTime(8,15,0); sunrise.hour = 8; // what is wrong?
This is a private member of the class
13
User Defined Type With a Class
• The class name becomes a new type specifier
• Note a function in the declaration with the same name as the class– this is the "constructor"– called automatically when object instantiated– explicitly (and correctly) initializes private
elements of the class
• Note the program figure 6.3, pg 371-2
14
User Defined Type With a Class
• Clients (objects) of the class use the class without knowing internal details of function implementation– changes in implementation do not affect client
usage
• Data (usually private) is validated by the constructor and by member functions each time it is modified
• Member functions have fewer parameters – they are accessing private data
15
User Defined Type With a Class
• Note that clients have access to a class interface– But … they should NOT have access to class
implementation
• Note– member functions declared INSIDE class definition– member functions are defined (source code body)
OUTSIDE class definition– clients can see class definition without seeing the
source code of the functions
16
Information Hiding
• Class members can be public or private• Public members accessible outside the
class - provide the interface• Private members not accessible outside
the class– accessed by calling public members
(functions) to manipulate the private members
17
Class Specification
• Syntax for specifying members
class class_name { public : functions variables . . . private : variables
functions };
18
Class Specification
• Syntax for specifying functions
type class_name::function_name (param_list) { function body }
Note the scope operator
- class name specifies to which class this function belongs
Note the scope operator
- class name specifies to which class this function belongs
19Creating Classes for Programming
• Class declaration goes in a .h file– also called a specification file
• Definitions of class functions goes in a .cpp file
• The .cpp file is compiled separately from a client source code file
• The client program uses the #include command to reference the .h file
• A Borland C++ project file (.prj) enables the linking of all the .obj files
20
#ifndef COMPLEX_H#define COMPLEX_H#include <fstream.h>class Complex { // numbers of form a + b*i public:
Complex (); Complex (float, float); float Show_real () const; float Show_imag () const; void Set (float, float); void Print (ostream &out) const;
private: float a, b;
} ;#endif
#ifndef COMPLEX_H#define COMPLEX_H#include <fstream.h>class Complex { // numbers of form a + b*i public:
Complex (); Complex (float, float); float Show_real () const; float Show_imag () const; void Set (float, float); void Print (ostream &out) const;
private: float a, b;
} ;#endif
Specification File
• Create the .h file
Prevent multipledeclarations atcompile time
Prevent multipledeclarations atcompile time
ConstructorsConstructors
Access functionsAccess
functions
Function toalter private
variables
Function toalter private
variables
21
Implementation File
• Create .cppfile,
#include "complex.h"#include <fstream.h>#include <iomanip.h>
Complex::Complex (){ a = 0; b = 0; }
Complex::Complex (float real_part, float imag_part){ a = real_part; b = imag_part; } . . .
float Complex::Show_imag () const { return b; }
void Complex::Set (float real_part, float imag_part){ a = real_part; b = imag_part; } . . .
#include "complex.h"#include <fstream.h>#include <iomanip.h>
Complex::Complex (){ a = 0; b = 0; }
Complex::Complex (float real_part, float imag_part){ a = real_part; b = imag_part; } . . .
float Complex::Show_imag () const { return b; }
void Complex::Set (float real_part, float imag_part){ a = real_part; b = imag_part; } . . .
Required hereand in client code
Required hereand in client code
No type specifiedfor constructors
No type specifiedfor constructors
Use name ofclass and scope
specificationoperator : :
Use name ofclass and scope
specificationoperator : :
Type or void specifiedType or void specified
22
Creating a Project
• From the Turbo C++ pulldown menu, choose Project, then New
23
Creating a Project
"UnChoose" Class Library, then Runtime will be the only option chosen.
"UnChoose" Class Library, then Runtime will be the only option chosen.
Next choose"Advanced"
Next choose"Advanced"
Specify project nameSpecify project name
Specify EasyWin [.exe]Specify EasyWin [.exe]
24
Creating a Project
• Click both of these options off
• When you choose OK hereand in the Target Expert dialog box, then a project is created and a project window appears.
25
Creating a Project
• Right click on the .exe line and a popup window appears
• Choose adda node anda file choicebox appears
• Specifyfile withclass sourcecode to be added to the project
26
Creating a Project
• Note that the implementation file is nowshowing as part ofthe project
• Double click onthe .cpp file listed in the project will open the window for that source code
• Note that we only include the .cpp files into the project, NOT the .h files
27Class Scope and Accessing Class Members
• What belongs to a class's scope?– class data members declared in the class definition
– member functions declared in the class definition
• Within a class's scope class members are immediately accessible– no need for use of dot operator
• Outside scope, access is limited– objects of that type access public elements
– functions used to manipulate private elements
28
Accessing Class Members
• Using the declarations:– print for variable
sunrise– set time for element
3 of time_list– print for where
pointer references
class Time { public: Time(); void setTime( int, int, int ); void printMilitary(); void printStandard(); private: int hour; // 0 - 23 int minute; // 0 - 59 int second; // 0 - 59 };. . .Time sunrise, time_list[5], *time_ptr;
class Time { public: Time(); void setTime( int, int, int ); void printMilitary(); void printStandard(); private: int hour; // 0 - 23 int minute; // 0 - 59 int second; // 0 - 59 };. . .Time sunrise, time_list[5], *time_ptr;
sunrise.printMilitary( )
time_list[3].setTime(12,15,0 )
time_ptr->printStandard( )
29
Specification and Implementation
• Specification describes behavior of the data type without reference to its implementation
• Implementation hides – the concrete data representation– the code for the operations
30Separating Interface from Implementation
• Makes it easier to modify programs– calls to the class functions by objects of the
class type need NOT be changed
• Clients of the class do not need source code, merely the definition which specifies the interface– if you write a slick set of tools, you can sell
the .obj code with the class definitions (.h files) without revealing HOW you did things
31
Controlling Access to Members
• Note member access specifiers– public– private
• Used to control access to a class's data members and member functions
• Default is private– members accessed only by member functions
• Public– accessed by client in any function in the program
32
Controlling Access to Members
• Primary purpose of public members– present to class clients view of services class
provides– forms public interface of the class– clients not concerned with how tasks performed
• Private members– usually the data members– also functions that perform local
implementation
33
Controlling Access to Members
• Given declaration
How should these be done?
Time t;t.hour = 7;cout << "minute = "<<t.minute
t.setTime(7,0,0)
t.printStandard();
34
Controlling Access to Members
• How to access a class's private data– use access functions– return values of private data without allowing
change– can display private data formatted if desired
• How to change a class's private data– use modifier functions– guarantees valid changes
35
Categories of Member Functions
• Read and return the value of private data members
• Set value of private data members• Implement features of the class• Perform routine chores for the class
– initialize class objects– assign class objects– convert between classes and built in types– convert between classes and other classes– handle memory for class objects
36Access Functions and utility Functions
• Not all member functions need be made public
• They can be private and serve as utility functions
• Note figure 6.7 -- utility function totalAnnualSales();
• Only the other functions within the class can use this function
37Initializing Class Objects : Constructors
• A class member function with same name as the class
• It is invoked automatically each time an object of that class is instantiated
• Constructors can be overloaded– multiple versions of the function with same
name– versions differ by number and/or type of
parameters
38
Comments about Constructors
• Don't try to initialize data in the class definition– must take place in implementation
• Do not declare a return type for the constructor• The programmer should nearly always provide
a constructor for a class• The constructor ensures valid initialization
– modifier functions should be written to maintain that validity
39Default Arguments with Constructors
• Note example in figure 6.8public: Time (int = 0, int = 0, int = 0); //default constructor . . . Time::Time (int hr, int min, int sec) . . .
• These are default arguments
• Even if no (or part of the values) are provided at declaration time, the default values are used as needed(note instatiation, fig 6.8-4)
40
Constructors
• Declare default function argument values only in the prototype – NOT in the implementation
• Note that the Time constructor calls setTime– This is good practice -- makes program easier
to maintain
41
Using Destructors
• Declaring a destructor– use name of class preceded by a tilde ~
• Destructor acts as the complement of the constructor– Called when object is destroyed– Performs termination housekeeping
• Destructor has no parameters, returns no value
• Only one destructor allowed (no overloading)
42Calling Constructors and Destructors
• They are called automatically (never explicitly)
• Order of call– constructors called for objects defined in global
scope before any other function in that file begins execution
– even before main( )– Corresponding destructors called when main
terminates or exit function called
43Data Members and Member Functions
• Private data members manipulated only by member (and "friend") functions– class provides public member functions to do this– functions usually provided to "get", others
provided to "set" values (See fig 6.10)
• Note this is NOT the same as making the data public– the class functions make sure that only valid
changes are made and that the "get" does not actually alter private data values
44A Subtle Trap : Returning Reference to Private Data
• Reference variables act as an alias for the name of the object
• Public function for setting a private variable can be specified to return a reference (or a pointer) – see sample program in Fig. 6.11
• This combination violates encapsulation of the class– makes possible dangerous access to private data
values
45Assignment by Default memberwise Copy
• Consider two instances of type DateDate date1(3,5,99), date2;date2 = date1;
• This copies each member of object on right to object on left of =
• Similar type of copy of each member occurs with value parameter -- actual parameter values passed to formal parameter location
date1:mo:3day:5year:99
date2:mo:day:year:
46
Software Reusability
• Focus on use of classes (object oriented programs) make possible general classes that are applicable to other projects
• Class libraries exist and may be searched for classes which you can use or adapt for your project
• Text talks of need for ways to catalog these classes, license schemes, etc. so that they may be better reused.