Unit2 OOProgramming
Unit2 OOProgramming
Object-Oriented Programming
with C++
¾Overview of Object-Oriented Programming
¾C++ Classes
¾Constructors
¾Pointers and Dynamic Objects
¾Destructors
¾Overloading Operators
¾Conversion Operators
¾Memory Organization
¾Dynamic Memory Allocation
¾Input/Output
private:
double x; // x coordinate
double y; // y coordinate
};
Unit 2- OO Programming 5
Unit 2- OO Programming 6
Class Point, Source File (cont’d)
double Point::getY() const
{
// Accessor member function
double a;
// PRE: None
double b;
// POST: The current Y coordinate is returned
{
a = x + xDistance;
return y;
b = y + yDistance;
}
return Point( a, b );
double Point::distanceFromOrigin() const
}
// Accessor member function
// PRE: None
void Point::print() const
// POST: The distance to the origin is returned
// Accessor member function
// Library facilities used: sqrt() from cmath
// PRE: None
{
// POST: The current coordinates of the Point is
return sqrt( x * x + y * y ); printed
} // Library facilities used: cout object and
operator<< from iostream
Point Point::translate( double xDistance, double {
yDistance ) const cout << "( " << x << ", " << y << " )";
// Accessor member function }
// PRE: xDistance and yDistance are the
horizontal and vertical displacements.
// POST: A Point located at the result of the
translation is returned
Unit 2- OO Programming 7
Point p;
Point q(2,3);
double a = 1;
a = p.x; // Error
p.x = a; // Error
a = p.getX() // a becomes 0
p.print() // prints: (0,0)
q.print() // prints: (2,3)
a = (p.translate(5,10)).getX() // a is 5
Note:
Objects of a class are initialized by the class constructors or initializers.
Private members are only accessible inside the class definition.
Public operations (methods) are applied to an object
¾ i.e. p.print
This object is the implicit argument of the operation.
A const at the end of the function header means the implicit argument is not
modified.
Unit 2- OO Programming 8
Constructors (or Initializers)
Constructors are special operators used to initialize an object.
Are not real functions:
¾ have the same name as the class
¾ are not called explicitly
¾ do not have a return type
A class may have multiple constructors (with different arguments)
Constructors of a class X are invoked when
¾ a variable of class X is declared i.e.
Point p;
Point q(2,3);
¾ a temporary object is created; i.e.
a = Point(3,4);
return Point(2,3);
¾ a function with a parameter X is called
i.e. suppose distance is a function calculating the distance between two points
a = distance(p, q)
¾ a function returning X returns, i.e.
p.translate(5,10);
¾ a variable with a member X is initialized.
Unit 2- OO Programming 9
Class Invariants
Special assertions that are true by any member of the class
Example: The design for the Point class should contain the
following class invariant.
¾ The coordinates of any point are always defined.
OR
¾ getx and gety always return a value
Unit 2- OO Programming 10
Pointers and Dynamic Data
A pointer is a variable whose value is the memory address of another data
structure.
A pointer declaration:
<type>* <variable>
E.g.
int *ip, *iq;
Point* pp;
Note:
¾ The type of pp is pointer to Point.
¾ The declaration allocates space for pp, but not for any point.
Unit 2- OO Programming 11
Unit 2- OO Programming 12
Notation we Use with Pointers
Consider the following declarations:
Declaration Address Memory cells Name
int x = 5; 3000 5 x
int y = 10 5000 10 y
int * p; 5000 p
When we execute
p = &x;
3000 is placed in the memory slot for p
We say that p points to x and we show it :
p x
5
Unit 2- OO Programming 13
Unit 2- OO Programming 15
Unit 2- OO Programming 17
Example:
int* ip, *ap;
ip = new int;
ap = new int[50];
Point * r, *s;
r = new Point(3,4);
s = new Point[20];
The last example calls Point()
with each s[i] (i = 0 to 19).
Unit 2- OO Programming 18
Deallocation of Dynamic Data
When the delete operator is applied to a pointer that
points to a dynamic object, it frees the space the pointer
points to
¾ The pointer is then considered unassigned.
Example:
¾ delete ip;
delete [] ap;
Good Idea:
After deleting the space, set the pointer to NULL.
Destructors
The destructor for a class X is a method with name ~X().
¾ It has no arguments and no return type.
¾ It cannot be called; it is invoked by the system.
The destructor ~X is invoked:
¾ at the end of the scope of a variable of type X
¾ when delete is applied to a variable of type X*
¾ at the end of a function with an argument of type X
¾ to destroy temporaries after their use
¾ when a variable with an X member is deleted.
When the delete operator is applied to a pointer, it
¾ invokes the destructor of the class first
¾ then recycles the storage pointed to by the pointer.
If p is an array of n objects of class X, then
delete [] p ;
applies the destructor of X to each element of the array p
then deletes the array p itself.
A destructor is needed for composite objects that contain dynamic data
For simple objects like Point, it is not necessary.
Unit 2- OO Programming 20
Example: Integer Vector
An implementation of arrays of integers that
¾ check for out-of-range condition
¾ can be assigned.
The code can be found in the examples in following files:
IntVector Class Header File
IntVector Class Source File
IntVector Class Test Driver
Note:
The destructor has to deallocate all the dynamic data
allocated by the member functions.
Unit 2- OO Programming 21
Unit 2- OO Programming 23
Function Overloading
Use the same name for different (but similar) functions
¾ i.e. define the functions length for a string and an array of int
Unit 2- OO Programming 26
Operator Overloading
You can redefine in any class the built-in operators:
+, - , ..., =, ++, ..., [], <<, ..., etc.
Except
::, . , sizeof ?:
An overloaded operator:
¾ must have at least one class (or struct) argument
¾ has the same number of arguments, precedence and associativity as the built-in operation
¾ if its first argument is of class X, it can be declared as a member of X; otherwise it should be
a non-member.
Example:
In the following we’ll use the Complex class (representing complex numbers):
Complex Class Header
Complex Class Source
Complex Class Test Driver
We’ll define a + operator (to add two complex numbers).
Unit 2- OO Programming 27
Unit 2- OO Programming 28
Example: Overloading [] in IntVector
Code:
int& IntVector::operator[](int i) {
if ( i < low || i > high ) {
cerr << "Index out of range\n";
exit(1);
}
return value[i - low];
}
Unit 2- OO Programming 29
E.g.
char( 5*20 ) converts the result into a character;
(int *)( p+2) converts the result into a pointer to an integer.
Unit 2- OO Programming 30
Example
Suppose in the class Complex we define:
class Complex {
public:
Complex()
// regular constructor
{
realPart = 0; imaginaryPart = 0;
}
Complex( double a, double b )
// regular constructor
{
realPart = a; imaginaryPart = b Then we can do:
}
Complex( double d ) Complex C;
// typecasts double to Complex
{
double d = 5;
realPart = d; imaginaryPart = 0 C = Complex(d);
}
...
Unit 2- };
OO Programming 31
Variable Kinds
A C++ program may have many source files with many classes and functions.
A variable has two characteristics:
¾ extent or lifetime
¾ visibility or scope
C++ has 4 types of scope:
¾ local (internal)
– variable is known only inside the block in which it is declared.
¾ global (external)
– variable is declared outside of any function or block
– is known throughout any source file in which it is declared. i.e. extern variables, functions
and classes
¾ file
– its scope is the source file in which it is declared
– it cannot be used in any other file, i.e. static variables
¾ class or struct
– the scope of a variable which is a member of a class or structure is that class or structure
A variable can have one of the following 3 extent types:
¾ automatic
– created whenever the block in which it is declared is executed;
– destroyed whenever the block is exited.
¾ dynamic
– its memory is explicitly allocated and destroyed using new and delete
¾ static
– created when program is loaded in memory and retains its value until the end of the
program (i.e. retains its value between calls)
The scope of a static name cannot exceed the source file in which it is declared.
Unit 2- OO Programming 32
Example
Consider the following program ;
Memory Organization
There are a number of 'segments' in memory when a C++ program is
running. The following segments are standard:
Code Segment :
¾ also known as 'text' segment
¾ it contains machine language code produced by the compiler
¾ contains constant data
– e.g. const double e = 2.71828182845905
Static Data Segment:
¾ contains all data that have been declared static
¾ they are allocated when the program is loaded, and remain in memory until the
program terminates
¾ Only static data are allocated in the data segment (i.e. static functions are not)
¾ For instance, if we define
static int k;
static void foo(void)
{
static int i = 1;
....
}
i and k will be allocated in this segment.
Unit 2- OO Programming 34
Memory Organization (con’t)
Stack Segment
¾ it contains automatic variables (including arguments) and
¾ bookkeeping information as below
Heap Segment
¾ consists of (dynamic) storage allocated via new
¾ data stored in heap segment are not named; access is indirect via
pointers
Pictorially,
Code (Read Only)
Heap (RW)
free (RW)
Stack (RW)
Unit 2- OO Programming 35
Unit 2- OO Programming 36
Example
Suppose foo is defined as:
int foo(int a)
{ static int b = 0; return address
int c = a;
b += a; 5 (a)
return a + b + c;
5 (c)
}
return value
When foo(5) is called, the stack frame might
look like that on the right ...
Unit 2- OO Programming 39
New Operator
its argument is a type (or class)
it searches the heap to find a space big enough for an object of the
given type
if there is enough space
¾ it claims the space found and marks it as occupied
¾ returns the location's address
new can be used with two arguments: a type and a positive integer
n, in which case it allocates space for n objects of this type
i.e.
p = new Point(3,4); // one point
a = new Point[100]; // 100 points
Unit 2- OO Programming 40
Delete Operator
its argument is a pointer
it frees the space occupied by the object the pointer
points to
its argument remains unchanged
if its argument is NULL, it does nothing
it will cause an error if you delete a space not previously
allocated by the new operator
if par is a dynamic array of pointers to some type
delete [] par;
will apply delete to each element of par before it deletes
the space par points to.
Unit 2- OO Programming 41
Memory Fragmentation
Inherent in dynamic allocation is the concept of
fragmentation.
Heap is divided into a large number of small fragments.
Degree of fragmentation depends on the allocation
strategy in use. Three allocation strategies are:
¾ first fit : find the first suitable segment
¾ best fit : find the smallest suitable segment
¾ worst fit : find the largest suitable segment
Unit 2- OO Programming 42
Dangling Pointers
A dangling pointer is a pointer whose value int * p;
is the address of a storage block which has p = new int;
been freed. ...
*p = 20;
Consider the code on the right
...
¾ The error here is in the last line
delete p;
¾ We can't dereference p, since freeing the
...
node it pointed to made p invalid (dangling
pointer)
*p = 5;
¾ The effect is indeterminate. int * p;
p = new int;
The second box on the right shows a case ...
in which more than 1 pointer points to the *p = 20;
same object int* q = p;
¾ it might not be at all apparent that q is ...
invalid delete p;
...
*q = 5;
Unit 2- OO Programming 43
Unit 2- OO Programming 44