1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data...

46
1 Classes and Data Abstraction

Transcript of 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data...

Page 1: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

1

Classes and Data Abstraction

Page 2: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

2

Objectives

• Understand encapsulation and data hiding

• Understand data abstraction and Abstract Data Types (ADTs)

• Create and use C++ ADTs (classes)

Page 3: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 4: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 5: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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;};

Page 6: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 7: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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);

Page 8: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 9: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

9

Solution

• Use

class

• Takes care of initialization

• Implementation is – locally done– separate from usage

• Interface remains standardized

Page 10: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 11: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 12: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 13: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 14: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 15: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 16: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 17: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

17

Class Specification

• Syntax for specifying members

class class_name { public : functions variables . . . private : variables

functions };

Page 18: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 19: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 20: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 21: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 22: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

22

Creating a Project

• From the Turbo C++ pulldown menu, choose Project, then New

Page 23: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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]

Page 24: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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.

Page 25: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 26: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 27: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 28: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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( )

Page 29: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 30: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 31: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 32: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 33: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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();

Page 34: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 35: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 36: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 37: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 38: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 39: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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)

Page 40: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 41: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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)

Page 42: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 43: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 44: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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

Page 45: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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:

Page 46: 1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.

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.