0% found this document useful (0 votes)
21 views

Unit2 OOProgramming

The document discusses object-oriented programming concepts like classes, objects, encapsulation, and polymorphism. It provides an example of a Point class in C++ with details on its header file defining the class interface and source file defining member functions. The Point class encapsulates x and y coordinates as private data members and provides public accessor functions to get/set the values while maintaining class invariants. Constructors initialize new Point objects, and the class can be used to declare Point variables and call member functions to work with point objects in a program.

Uploaded by

Mahesh Mutnale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Unit2 OOProgramming

The document discusses object-oriented programming concepts like classes, objects, encapsulation, and polymorphism. It provides an example of a Point class in C++ with details on its header file defining the class interface and source file defining member functions. The Point class encapsulates x and y coordinates as private data members and provides public accessor functions to get/set the values while maintaining class invariants. Constructors initialize new Point objects, and the class can be used to declare Point variables and call member functions to work with point objects in a program.

Uploaded by

Mahesh Mutnale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Unit 2

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

Object-Oriented Programming (OOP)


„ Programs are collections of objects
„ Computation is done by sending messages to objects
„ Objects have 3 characteristics
¾ state
¾ behavior
¾ identity
„ Example: bank accounts state: id, name, balance
¾ behaviour: deposit, withdraw, etc.
¾ identity: Joe's account is similar but different than Jane's
„ A class is a group of objects with the same behavior and representation.
¾ A class defines an abstract data type
– it defines the state variables and operations (methods) for its objects.
¾ A class may inherit characteristics from ancestor classes.
¾ Objects are instances of classes.

„ Fundamental characteristics of OOP languages are:


¾ encapsulation
¾ instantiation
¾ inheritance
¾ polymorphism
Unit 2- OO Programming 2
C++ Classes
„ A class declaration or signature consists of:
¾ class name
¾ declarations of private members (data and operations )
¾ declarations of public members (data and operations)

„ A class definition consists of:


¾ a class declaration, and
¾ definitions of the member functions (operations)

„ It is customary to treat a class as a module, splitting its definition is a


specification and implementation files

„ The specification or header file of a class X


¾ contains the class declaration
¾ is named X.h
.
„ The implementation or source file of a class X
¾ contains the definitions of the member functions
¾ is,named X.cpp or X.C .

„ Any file that uses X can include X.h.


Unit 2- OO Programming 3

Example: Class Point, Header File


// file: Point.h Point( double x1, double y1 );
// Point class header // Parameterized constructor
// PRE: x1 and y1 are two valid doubles.
#ifndef POINT_H // POST: A new Point object is created with (
#define POINT_H x1, y1 ) as its coordinates

class Point double getX() const;


// Accessor member function
// The Point class defines a point on the // PRE: None
Cartesian plane in terms of x and // POST: The current X coordinate is returned
// y coordinates. The class has both a default
and parameterized
// constructors. double getY() const;
// Accessor member function
// Class Invariants: // PRE: None
// - The coordinates of a Point are always // POST: The current Y coordinate is returned
defined
// - getX() and getY() always return a value double distanceFromOrigin() const;
{ // Accessor member function
public: // PRE: None
// POST: The distance to the origin is returned
Point(); // Library facilities used: sqrt() from cmath
// Default constructor
// PRE: None
// POST: A new Point object is created with ( #endif
0, 0 ) as its coordinates
Unit 2- OO Programming 4
Class Point, Header File (cont’)
Point translate( double xDistance, double
yDistance ) const;
// 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

void print() const;


// Accessor member function
// PRE: None
// POST: The current coordinates of the Point
is printed
// Library facilities used: cout object and
operator<< from iostream

private:

double x; // x coordinate
double y; // y coordinate

};

Unit 2- OO Programming 5

Class Point, Source File


// file: Point.cpp
// Point class source Point::Point( double x1, double y1 )
// Parameterized constructor
#include <iostream> // used in print() // PRE: x1 and y1 are two valid doubles.
#include <cmath> // used in // POST: A new Point object is created with ( x1,
distanceFromOrigin() y1 ) as its coordinates
#include "Point.h" {
using namespace std; x = x1;
y = y1;
// Note: This module uses the sqrt() function in }
the math library.
// So when producing a final executable file
using this module, double Point::getX() const
// the math library must be linked in. // Accessor member function
// PRE: None
Point::Point() // POST: The current X coordinate is returned
// Default constructor {
// PRE: None return x;
// POST: A new Point object is created with ( 0, }
0 ) as its coordinates
{
x = 0;
y = 0;
}

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

Using the Point class


„ Now, Point can be used as a new type:

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

„ They are denoted by Class Invariants:


¾ in the design of the class, or
¾ as a comment at the beginning of the header file for the class

„ For any class:


¾ a constructor
~ must satisfy the Class Invariants upon its return
¾ a member function
– assumes that Class Invariants are true at invocation
– must ensure that Class Invariants are true upon its return

„ 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.

„ Functions can also return pointer values.


i.e. int* f(int x)
f returns an address of an integer.

„ C and C++ permit a variety of operations on pointers including


¾ dereference
¾ pointer arithmetic

Unit 2- OO Programming 11

The operators * and &


„ Are used to manipulate pointers:
¾ * is the dereference or indirection operator
– used to dereference a pointer value.
¾ & is the address-of operator
– gives the address of an object.

„ Example: Demonstrating the use of * and &.


int x, y;
int* ip;
x = 2;
y = 3;
ip = &x; // ip points to x now
y = *ip; // the value of y is now 2
*ip = 0; // the value of x is now 0
(*ip)++; // the value of x is now 1

„ The address of an object cannot be changed.


&x = &y is not permitted.

„ & is used to pass the address of a parameter to a function.

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

Example Using * and &


„ To swap the values of two integer variables we can
define the function
void swap ( int *a, int *b )
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
„ Suppose x and y are defined as
int x = 5, y = 10;
To swap them we can call
swap(&x, &y);
Unit 2- OO Programming 14
References and Pointers
„ A variable can be declared to be a reference to type:
<type>& <variable>
i.e.
int i;
int& p = i; // p is an alias of the integer object i

„ A reference is another name for the location it refers to.


i.e. in the previous example i and p are names of the same location
p = 5;
causes i to be 5.

„ References are usually used for parameter passing .

Unit 2- OO Programming 15

Example with References


„ The swap function can be written as:
void swap( int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Then if we have declare
int x = 5, y=10;
we can swap them by calling
swap(x, y);
Unit 2- OO Programming 16
Dynamic Data
„ C++ has three kinds of data:
¾ automatic data - allocated, deallocated automatically
¾ static data - exists throughout the program
¾ dynamic data - allocated, deallocated by the programmer

„ We’ll discuss how dynamic data are allocated and


deallocated.

Unit 2- OO Programming 17

Allocation of Dynamic Data


„ When the new operator is applied to a constructor,
¾ an object of the class is generated
¾ the address of the object is returned

„ 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.

„ If the address (pointer value) is NULL and apply delete


to it, nothing happens.
Unit 2- OO Programming 19

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

Copy Constructors (or Copy Initializers)


„ A copy initializer for a class C is a constructor of the form
C(const C&)
„ It is used automatically when copying occurs.
„ Copying an object occurs
¾ at an assignment
¾ at initialization
¾ passing arguments (by value)
¾ returning values from a function

„ In the first case, the assignment operator is used.


In the rest, the copy constructor is used.

„ If no constructor is defined, the system performs a shallow copy


(or memberwise copy ):
¾ only the top members of the object are copied

„ If the object has dynamic members


¾ a deep copy is required
¾ a copy constructor and an assignment operator must be defined
Unit 2- OO Programming 22
Shallow vs. Deep Copy
„ Suppose we execute
IntVector a(5,10);
IntVector b = a;

Unit 2- OO Programming 23

Example: Copy Constructor for IntVector


class IntVector IntVector::IntVector( const IntVector& someVector )
{ // Copy constructor
public: {
copy( someVector );
IntVector(); }
// Default constructor

IntVector( int l, int h ); void IntVector::copy( const IntVector& someVector )


// Parameterised constructor
// Private member helper function that copie
IntVector( const IntVector& // the contents of IntVector
someVector ); // 'someVector' into the current IntVector
// Copy constructor {
…. low = someVector.low;
private: high = someVector.high;
value = new int[ high - low + 1 ];
int* value; // Pointer to a dynamically-
allocated array of integers for ( int i = 0; i <= high - low; i++ )
int low; // the lower index bound {
int high; // the upper index bound value[i] = someVector.value[i];
}
void copy( const IntVector& someVector ); }
// Helper function used by copy constructor
}
Unit 2- OO Programming 24
Friends
„ If we want a function or method f defined outside a class C to have access to the
private members of C, we declare (in class C) f to be a friend of C.

„ Example: Function Friend


Declaring distance function to be a friend of Point:
class Point {
friend double distance(Point, Point);
....
}

double distance(Point a, Point b) {
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
„ A class A can also declare another class B to be a friend.
B can then access the private members of A.

„ Example: Class Friend


If we want the class Triangle to have access to Point we define:
class Point
{
friend class Triangle;
.....
Unit 2- OO Programming 25

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

„ At a call, C++ chooses one of them according to the


argument type as follows:

¾ if an exact argument type match is found, the corresponding


function is called
¾ if a unique match is found after type promotions, the
corresponding function is called
¾ if a unique match is found after type conversions, the
corresponding function is called

Unit 2- OO Programming 26
Operator Overloading
„ You can redefine in any class the built-in operators:
+, - , ..., =, ++, ..., [], <<, ..., etc.
Except
::, . , sizeof ?:

„ An overloaded operator can be defined as:


¾ a member function in a class, or
¾ a friend of a class

„ 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

Example: Overloading + in Complex


„ As a non member: I
„ In this case, we can use it
It should be declared as friend in Complex
using the functional notation
c = operator+(a, b);
Complex operator+(Complex x, Complex y)
{ or the operator notation
return Complex(x.realPart + y.realPart, c = a + b;
x.imaginaryPart +y.imaginaryPart);
}

„ As a member: „ In this case, we can use it


using the functional notation
Complex Complex::operator+( Complex y) c = a.operator+(b);
{ or the operator notation
return Complex( realPart + y.realPart, c = a + b;
imaginaryPart + y.imaginaryPart);
}

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

„ Then we can do the following:


IntVector a(5,10), b(1,20);
a[5] = 0;
b[1] = a[5];

„ See examples for the complete code (that includes [] and =


operators) for IntVector

Unit 2- OO Programming 29

Type Conversion Operators


„ Built-in types are automatically converted to different Built-in types if this is
necessary and possible:
¾ during the evaluation of a sub-expression
¾ across assignments
¾ at a function call (where the expression is the argument)
¾ at a function return (where the expression is the return value)

„ For built-in types:


¾ user can enforce conversions by using type coercion or type casting of the form:
„ type-name( expression )

„ E.g.
char( 5*20 ) converts the result into a character;
(int *)( p+2) converts the result into a pointer to an integer.

„ For defined classes,


¾ an explicit conversion from class X to Y can be performed by defining in Y a
constructor of the form Y(X) or Y(X&).

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 ;

int k; static void q( void )


static int i; { k = 1;
void p( int a ) p( k );
{ static int b = 50; }
int c;
int *w = new int; void main()
c = a + a; { int k = 2;
b += c; p( k );
} }
The characteristics of the variables are summarized in the following table
local file global
automatic a,c,w,k (in main) ---------------- k (first line),p
static b i, q ---------------------
dynamic block ref'd by w
Unit 2- OO Programming 33

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)

Static (Read Write)

Heap (RW)

free (RW)

Stack (RW)
Unit 2- OO Programming 35

The Run-time Stack


„ When a procedure is called the system builds a stack
frame for the call and pushes it on the top of the stack
„ When the procedure returns, the system pops the frame
from the stack
„ A stack frame contains space for:
¾ parameters
¾ local automatic variables
¾ return value
¾ return address
¾ other bookkeeping information
¾ a pointer to the previous frame

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 ...

„ Recursion is done by pushing an additional


frame onto the stack. Some C compilers pointer to
'recognize' tail recursion and do not push an |previous frame
additional frame.
Unit 2- OO Programming 37

Static Var’s and the Stack


„ Static variables are NOT stored on the stack:
¾ they are stored in the static segment
¾ they are allocated and initialized exactly once

„ Example: Consider the following function.


int count()
{ static int j = 0;
j++;
return j;
}
int main()
{ cout << "first " << count()<< " second " << count()<< " third " <<
count()<< "/n";
}

This produces the output:


first 1 second 2 third 3
which clearly shows that only one location is used for j.
Unit 2- OO Programming 38
Dynamic Memory Allocation
„ Often it is necessary for the program to allocate memory
as it is needed:
¾ data size is not known in advance
¾ size of data varies widely
¾ most objects need to be created at run time
¾ most objects need to be dynamic
„ This is called dynamic memory allocation and is done by
operators new and delete (as we have seen).
„ Dynamic data created this way
¾ is on the heap
¾ is accessible through pointers only
¾ has dynamic extent
¾ is accessible by any part of the program (as long as the address
of the data is known)

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

„ if there is not enough space


¾ an exception is raised or a NULL is returned (depends onthe
implementation);

„ 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

Inaccessible Objects - Memory Leaks


„ A dynamic object with no pointer pointing to it is
inaccessible.
„ A memory leak is created by:
¾ inaccessible objects
¾ dynamic objects that are not needed anymore (and never
deleted)
„ In certain languages, objects cannot be explicitly freed.
These languages have a garbage collection or
scavenging system that frees objects no longer in use.
„ In C and C++, garbage collecting is done by the
programmer, whereas in Java and Scheme, the system
performs the garbage collection.

Unit 2- OO Programming 44

You might also like