Documente Academic
Documente Profesional
Documente Cultură
2014
Encapsulation
Chapter 6
Structures
and Classes
All C++ programs are composed of the following two fundamental elements:
Program statements (code): This is the part of a program that performs actions and they are called functions.
Program data: The data is the information of the program which affected by the program functions.
Encapsulation is an Object Oriented Programming concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and
misuse. Data encapsulation led to the important OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them and
data abstraction is a mechanism of exposing only the interfaces and hiding the
implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of userdefined types, called classes. We already have studied that a class can contain private,
protected and public members. By default, all items defined in a class are private. For
example:
Encapsulation
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double width; // width of a box
double height; // Height of a box
};
6-2
6-3
"Abstract"
Programmers dont know details
Abbreviated "ADT"
Collection of data values together with set
of basic operations defined for the values
6-4
21.12.2014
More Encapsulation
Principles of OOP
Information Hiding
Encapsulation
Data Abstraction
Details of how data is manipulated within
ADT/class not known to user
Object is "encapsulation" of
Data values
Operations on the data (member functions)
Encapsulation
Bring together data and operations, but keep "details"
hidden
6-5
6-6
class DayOfYear
{
public:
void input();
void output();
private:
int month;
int day;
};
6-8
21.12.2014
Declare object:
DayOfYear today;
today.input();
today.output();
6-9
6-10
Separate Interface
and Implementation
6-12
21.12.2014
Thinking Objects
Structures
Classes
Technically, same
6-13
Summary 1
6-14
Summary 2
6-15
6-16
21.12.2014
Chapter 7
Constructors and
Other Tools
Learning Objectives
Constructors
Definitions
Calling
More Tools
const parameter modifier
Inline functions
Constructors
Constructors
7-18
7-19
Initialization of objects
Initialize some or all member variables
Other actions possible as well
7-20
21.12.2014
Constructor Definitions
class DayOfYear
{
public:
DayOfYear(int monthValue, int dayValue);
//Constructor initializes month and day
void input();
void output();
private:
int month;
int day;
}
Except:
1. Must have same name as class
2. Cannot return a value; not even void!
7-21
Constructor Notes
7-22
Calling Constructors
Declare objects:
DayOfYear date1(7, 4),
date2(5, 5);
Constructor is called
Values in parantheses passed as arguments
to constructor
Member variables month, day initialized:
date1.month 7 date2.month 5
date1.day 4 date2.day 5
7-23
7-24
21.12.2014
Constructor Equivalency
Constructor Code
Constructor definition is like all other
member functions:
Consider:
DayOfYear date1, date2
date1.DayOfYear(7, 4);
date2.DayOfYear(5, 5);
// ILLEGAL!
// ILLEGAL!
Seemingly OK
7-25
Alternative Definition
7-26
DayOfYear::DayOfYear(
int monthValue,
int dayValue)
: month(monthValue), day(dayValue)
In initializer version
{}
7-27
7-28
21.12.2014
Overloaded Constructors
Can overload constructors just like
other functions
Recall: a signature consists of:
Name of function
Parameter list
7-29
7-30
7-31
7-32
21.12.2014
Can be confusing
// This way!
// NO!
Default Constructor
In Action:
DayOfYear holiday(7, 4);
Auto-Generated?
Yes & No
If no constructors AT ALL are defined Yes
If any constructors are defined No
If no default constructor:
7-34
7-35
7-36
21.12.2014
7-37
7-38
7-39
7-40
10
21.12.2014
7-41
7-42
Call-by-value
Requires copy be made Overhead
Call-by-reference
Placeholder for actual argument
Most efficient method
Call-by-reference desirable
Especially for "large" data, like class types
7-43
7-44
11
21.12.2014
Summary 1
Chapter 8
Operator
Overloading
7-45
Learning Objectives
Unary operators
As member functions
8-47
C++ allows you to specify more than one definition for a function name or
an operator in the same scope, which is called function
overloading and operator overloading respectively.
An overloaded declaration is a declaration that had been declared with
the same name as a previously declared declaration in the same scope,
except that both declarations have different arguments and obviously
different definition (implementation).
When you call an overloaded function or operator, the compiler
determines the most appropriate definition to use by comparing the
argument types you used to call the function or operator with the
parameter types specified in the definitions. The process of selecting the
most appropriate overloaded function or operator is called overload
resolution.
8-48
12
21.12.2014
Function overloading
#include <iostream>
using namespace std;
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
int main(void)
{
printData pd;
Think of it as:
+(x, 7)
return 0;
}
void print(char* c) {
cout << "Printing character: " << c <<
endl;
}
};
Copyright 2012 Pearson Addison-Wesley. All rights reserved.
7-49
8-50
Overloading Basics
Overloading operators
e.g., +, -, = , %, ==, /, *
Already work for C++ built-in types
In standard "binary" notation
Example Declaration:
8-52
13
21.12.2014
Overloaded "+"
Given previous example:
8-53
8-54
Overloaded "=="
Equality operator, ==
Enables comparison of Money objects
Declaration:
bool operator ==(const Money& amount1,
const Money& amount2);
Returns bool type for true/false equality
8-55
8-56
14
21.12.2014
8-57
8-58
(m1+m2).input();
PROBLEM!
//Legal!
8-59
8-60
15
21.12.2014
++, --
8-61
8-62
amount3.output();
//Displays $4.00
amount3 = -amount1;
amount3.output()
8-63
//Displays -$10.00
8-64
16
21.12.2014
8-65
8-66
Overloading Operators:
Which Method?
const Functions
Object-Oriented-Programming
(Later in chapter)
8-67
8-68
17
21.12.2014
Other Overloads
Example:
Aclass anObject;
anObject(42);
8-69
Summary 1
8-70
Chapter 10
Pointers and
Dynamic Arrays
8-71
18
21.12.2014
Learning Objectives
Pointer Introduction
Pointers
Pointer definition:
Pointer variables
Memory management
Dynamic Arrays
Call-by-reference parameters
Address of actual argument was passed
10-73
Pointer Variables
10-74
Example:
double *p;
10-75
10-76
19
21.12.2014
Pointing
Pointer is an address
Terminology, view
Talk of "pointing", not "addresses"
Pointer variable "points to" ordinary variable
Leave "address" talk out
Address is an integer
Pointer is NOT an integer!
Not crazy abstraction!
10-77
Pointing to
Pointing to
Recall:
int *p1, *p2, v1, v2;
p1 = &v1;
Operator, &
Determines "address of" variable
Read like:
Dereference operator, *
10-78
10-80
20
21.12.2014
& Operator
Consider:
v1 = 0;
p1 = &v1;
*p1 = 42;
cout << v1 << endl;
cout << *p1 << endl;
Produces output:
42
42
10-81
10-82
Pointer Assignments
Pointer variables can be "assigned":
int *p1, *p2;
p2 = p1;
Assigns one pointer to another
"Make p2 point to where p1 points"
10-83
10-84
21
21.12.2014
p1 = new int;
Creates new "nameless" variable, and
assigns p1 to "point to" it
Can access with *p1
Use just like ordinary variable
Copyright 2012 Pearson Addison-Wesley. All rights reserved.
10-85
10-86
Basic Pointer
Manipulations
Graphic:
Display 10.3
Explanation of
Display 10.2
10-87
10-88
22
21.12.2014
MyClass *mcPtr;
mcPtr = new MyClass(32.0, 17);
//Initializes *n to 17
10-89
Memory Management
10-90
Heap
Also called "freestore"
Reserved for dynamically-allocated variables
All new dynamic variables consume memory
in freestore
10-91
10-92
23
21.12.2014
Freestore Size
Varies with implementations
Newer compilers:
If new operation fails:
Typically large
Memory management
10-93
delete Operator
Dangling Pointers
delete p;
Destroys dynamic memory
But p still points there!
Example:
If p is then dereferenced ( *p )
int *p;
p = new int(5);
//Some processing
delete p;
Unpredicatable results!
Often disastrous!
10-94
10-95
10-96
24
21.12.2014
Local variables
10-97
10-98
10-99
10-100
25
21.12.2014
10-101
Dynamic Arrays
Array Variables
Recall: arrays stored in memory
addresses, sequentially
Array variables
Really pointer variables!
Standard array
Fixed size
Example:
int a[10];
int * p;
Dynamic array
Size not specified at programming time
Determined while program running
Copyright 2012 Pearson Addison-Wesley. All rights reserved.
10-102
10-103
10-104
26
21.12.2014
Array variable
int a[10];
int a[10];
typedef int* IntPtr;
IntPtr p;
Cannot be changed!
a = p; // ILLEGAL!
Array pointer is CONSTANT pointer!
Copyright 2012 Pearson Addison-Wesley. All rights reserved.
10-105
Dynamic Arrays
10-106
Array limitations
Very simple!
Example:
Dynamic arrays
Can grow and shrink as needed
Copyright 2012 Pearson Addison-Wesley. All rights reserved.
10-107
10-108
27
21.12.2014
Example:
int [] someFunction(); // ILLEGAL!
d = new double[10];
//Processing
delete [] d;
De-allocates all memory for dynamic array
Brackets indicate "array" is there
Recall: d still points there!
10-109
Pointer Arithmetic
10-110
Example:
typedef double* DoublePtr;
DoublePtr d;
d = new double[10];
d contains address of d[0]
d + 1 evaluates to address of d[1]
d + 2 evaluates to address of d[2]
Equivalent to:
for (int i = 0; i < arraySize; i++)
cout << d[I] << " " ;
10-111
10-112
28
21.12.2014
Yes we can!
Shorthand notation
Back to Classes
10-113
10-114
10-115
10-116
29
21.12.2014
s1 = s2 = s3;
Requires (s1 = s2) = s3;
So (s1 = s2) must return object of s1"s type
And pass to " = s3";
10-117
10-118
Destructor Need
Dynamically-allocated variables
Shallow copy
Assignment copies only member variable
contents over
Default assignment and copy constructors
Deep copy
In constructor
Answer: destructor!
10-119
10-120
30
21.12.2014
Destructors
Copy Constructors
Opposite of constructor
10-121
MyClass::~MyClass()
{
//Perform delete clean-up duties
}
Summary 1
Summary 2
Class destructor
Dynamic variables
Copy constructor
Freestore
Memory storage for dynamic variables
Assignment operator
Must be overloaded as member function
Returns reference for chaining
10-122
10-123
10-124
31