Beruflich Dokumente
Kultur Dokumente
Abstraction
Chapter 15
1
2
What a Class ! !
Specification
Classes
Private
Declaring we
classes
What
have and
andis a
already
data and
constructor?
public
implementation
seen
elements
functions
3
Data Type
domain operations
Categories of Operations
Constructor => create new instance
(variable) of Abstract Data Type (ADT)
complex c1, c2;
// constructor initializes a + bi
Categories of Operations
Observer => Allows a look at the
state of an instance of an ADT
without changing it.
complex c1, c2;
cout << c1.real_part();
C++ Classes
Data and Operations bound into a
single unit
– Like a struct which includes functions
to manipulate the data
class Complex
{ public :
void assign (float a, float b);
void print_complex ();
float real_part ();
. . .
private:
float a, b; } ;
9
Class Operations
Class Scope
Name of a class member is local to
the class.
complex c1, c2;
int a, b, c;
. . .
c1 = c2;
cout << c1.real_part();
// but NOT
// cout << real_part
Information Hiding
Class object has an "invisible wall"
– called the abstraction barrier
Protects private data and functions
– client code cannot access private
elements
– client can access only public members
Think of a class as a "black box"
– it will act on the data
– but you need not
know how it works
16
Information Hiding
Class implementation details are hidden from the
client’s view. This is called information hiding.
client
specification implementation
code
17
Information Hiding
Encapsulation
Hiding of implementation details
Keeps client/user of the ADT from…
– depending on details
– incorrectly manipulating the details
18
Specification File
File which describes the behavior of
the data type
– does not reference the implementation
details
This is the .h file with the
prototypes, the declarations
Both the client and implementation
file will have
#include <xxxx.h> Example
19
Implementation File
Contains all the function definitions
– includes function heading
– includes body of function
Similar to function definitions below
main ( )
– except is in different file
Function headings in this file must
match prototypes in .h file
Example
20
private:
. . .
};
cin.get (someChar) ;
cin.ignore (100, ‘\n’) ;
22
Familiar Class Instances and
Function Members
Declare myInfile as an instance of
class ifstream.
ifstream myInfile ;
myInfile.open ( “A:\\mydata.dat” ) ;
Class constructors
Guarantee initialization of class
object
Constructor function has same
name as the class
Can have different versions of
constructor
Complex::Complex ( )
{ a = 0; b = 0;
Complex::Complex (int real_part,
int Imag_part)
{ a = real_part;
b = imag_part; }
24
Invoking a Constructor
Invoked automatically whenever a
class object is created (instantiated)
Example: