Sie sind auf Seite 1von 21

Object Oriented

Paradigm
Lecture # 06
Objects with Pointers,
References, and Arrays

Outline

Arrays of Objects

Memory Management: the new and delete


Operators

Defining Dynamic Objects

Pointer to Object

Reference to Object

Array of Pointers to Objects


2

Defining Arrays of Objects

We may define arrays of objects


In the example below we see an array with ten elements
of type Point
void main() {
Point array[10]; // defining an array with ten objects
array[0].move(15,40); // moving first object (index 0)
array[1].move(75,35); // moving second object (index 1)
// so on
for(int i= 0;i<10;i++) // printing all objects in the array
array[i].print();
}
3

Arrays of Objects
//distance.h
class Distance
{
private:
int feet;
float inches;
public:
Distance(int f=0,float i=0.0):feet(f),inches(i){}
void setFeet(int);
void setInches(float);
int getFeet();
float getInches();
};
4

Arrays of Objects
//distance.cpp
#include<iostream>
using namespace std;
#include"distance.h"
void Distance::setFeet(int f)
{feet=f;}
void Distance::setInches(float i)
{inches=i;}
int Distance::getFeet()
{return feet;}
float Distance::getInches()
{return inches;}
5

dist[i].setFeet(ft);
cin>>in;

Arrays of Objects
//client.cpp
#include"distance.h"
#include<iostream>
using namespace std;
void main(){
Distance dist[10];
int ft,i;
float in;
for(i=0;i<10;i++){
cout<<"enter
distance"<<endl;
cin>>ft;

dist[i].setInches(in)
;
}
for(i=0;i<10;i++){
cout<<dist[i].getFee
t()
<<endl;
cout<<dist[i].getInc
hes() <<endl;
}
}

Initializing Arrays of Objects

When an array of objects is created, the default


constructor of the class is invoked for each element
(object) of the array

Point array[10]; // Default constructor is called 10 times

To invoke a constructor with arguments, a list of initial


values should be used

To invoke a constructor with more than one arguments,


its name must be given in the list of initial values

Memory Management

We have seen examples where arrays are used to set


aside memory

Example
int arr[10];

Drawback with array is:

We must know array size at coding time

Following code wont work


cin>>size;
int arr[size];

Compiler requires array size to be a compile time


constant
8

The new Operator

Another approach to obtaining blocks of memory


is using new operator

This versatile operator obtains memory from the


operating system and returns a pointer to its
starting point

new returns a pointer to an unnamed object


9

The new Operator


#include<iostream>
#include<cstring>
using namespace std;
int main(){
char* str="Demonstrating new and delete operators";
int len = strlen(str);
char* ptr;
ptr = new char[len+1];//set aside memory: string + '\0'
strcpy(ptr, str);
cout << ptr << endl;
delete[] ptr;//release ptrs memory
return 0;
}
10

The new Operator


Data types must match

brackets

char *ptr = new char[len];

keyword
pointer

Number of type char variables

Data type of variables

11

The delete Operator

When new is used to allocate memory, delete


must be used to de-allocate the memory

Deleting the memory doesnt delete the pointer


to it and doesnt change the address value in the
pointer

However, this address is not valid anymore

Guideline: Dont use pointers to memory that


has been deleted
12

Defining Dynamic Objects

Classes can be used to define variables/objects


like built-in data types (int, float, char etc.)

It is also possible to define pointers to objects

In the next example, two pointers (pp1 and pp2)


to objects of type Point are defined and used
13

Defining Dynamic Objects


void main()

pp1->print(); // 'print'
message to the object

pointed by pp1

Point *pp1 = new Point;//

pp2->move(100,150);//

allocating memory for the

'move' message to the

object pointed by pp1

object pointed by pp2

Point *pp2 = new Point;//

delete pp1; // Releasing

allocating memory for the


object pointed by pp2
pp1->move(50,50);// 'move'
message to the object

the memory
delete pp2;
}

pointed by pp1
14

Pointers to Objects
void main( ) {
Distance dist1;
dist1.setFeet(10);
dist1.setInches(11.1);
cout<<dist1.getFeet()<<endl;
cout<<dist1.getInches()<<endl;

Comparing the two


approaches of
object creation

Distance *dist2=new Distance;


dist2->setFeet(20);//using membership access operator
dist2->setInches(22.2);//hyphen and greater than sign
cout<<dist2->getFeet()<<endl;
cout<<(*dist2).getInches()<<endl;
}
15

Pointers to Objects

Objects are stored in memory, so pointers can point to


objects just as they can to variables of basic types

The new Operator

The new operator allocates memory of a specific size from


the operating system and returns a pointer to its starting
point

If it is unable to find space, it returns a 0 pointer

When you use new with objects, it not only allocates


memory for the object, it also creates the object in the
sense of invoking the objects constructor.

This guarantees that the object is correctly initialized, which


is vital for avoiding programming errors
16

Pointers to Objects

The delete Operator

To ensure safe and efficient use of memory, the new


operator is matched by a corresponding delete
operator that releases the memory back to the
operating system

If you create an array with new, you need the brackets


when you delete it
int * ptr = new int[10];
:
delete [ ] ptr;
17

Reference to Object

A reference is simply an alias (another name) for


a variable

A parameter may be specified as a reference


type

During the function call, a copy of the argument


variable is not made, but the variable itself is
used instead

To specify a reference type, an ampersand (&) is


added after the type name
18

Reference to Object
// Using reference parameters
#include <iostream>
using namespace std;
int larger(const int& m, const int& n);
int main() {
int value1 = 10;
int value2 = 20;
cout << endl << larger(value1, value2) << endl;
cout << endl << larger(value1, 15) << endl;
return 0;
}
// Function to the larger of two integers
int larger(const int& m, const int& n)
{
return m > n ? m : n; // Return the larger value
}
19

Reference to Object

Passing an argument by reference can be used


to allow a function to modify a variable in the
calling program

The main motivation behind pass by reference is


efficiency: the entire variable is not copied

20

An Array of Pointers to
Objects

A group of objects can be stored by storing an


array of pointers to them, rather than storing the
objects themselves

This arrangement (array of pointers to objects)


allows easy access to group of objects, and is
more flexible than placing the objects
themselves in an array
21

Das könnte Ihnen auch gefallen