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

Lecture 4 - Arrays, Pointers and References

The document discusses arrays of objects in C++, including initializing and accessing array elements. It also covers using pointers to objects, the this pointer, and dynamic memory allocation using new and delete operators.

Uploaded by

emon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Lecture 4 - Arrays, Pointers and References

The document discusses arrays of objects in C++, including initializing and accessing array elements. It also covers using pointers to objects, the this pointer, and dynamic memory allocation using new and delete operators.

Uploaded by

emon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

8/17/2014

Lecture Four

Arrays, Pointers and References

Ref: Herbert Schildt, Teach Yourself C++, Third Edn (Chapter 3)

© Dr. M. Mahfuzul Islam


Professor, Dept. of CSE, BUET

Arrays of Objects

An array of objects is declared and accessed exactly the same way of


other type of variables.
If a class include a constructor, an array of objects can be initialized.

#include <iostream> int main() {


using namespace std; samp ob[4];
int i;
class samp {
int i;
for(i=0; i<4; i++) ob.set[i].set_i(i);
public:
void set_i(int n) {i= n;}
for(i=0; i<4; i++) cout << ob.set[i].get_i();
int get_i() { return i;}
};
return 0;
}

An array of objects can be initialized in two ways.

1
8/17/2014

Arrays of Objects
(1) For single argument:
(a) For 1D array:
#include <iostream> int main() {
using namespace std; samp ob[4] = {-1. -2. -3, -4};
class samp {
int i; for( int i= 0; i < 4; i++)
public: cout << ob[i].get_i() << ‘ ‘;
samp(int n) { i = n;}; cout << “\n”;
int get_i() { return i;} return 0;
}; }

(b) For 1D array alternative: (c) For 2D array:


int main() { int main() {
samp ob[4] = { samp(-1), samp(-2), samp ob[4][2] = {1, 2, 3, 4, 5, 6, 7, 8};
samp(-3), samp(-4)};
for( int i= 0; i < 4; i++) {
for( int i= 0; i < 4; i++) cout << ob[i][0].get_i() << ‘ ‘;
cout << ob[i].get_i() << ‘ ‘; cout << ob[i][1].get_i() << ‘ ‘;
cout << “\n”; }
return 0; return 0;
} }

Arrays of Objects

(2) For multiple arguments:


#include <iostream> int main() {
using namespace std; myclass ob[4] = {myclass(1, 2), myclass(3, 4),
class myclass { myclass(2, 4), myclass(4, 5)};
int a, b;
public: for( int i= 0; i < 4; i++)
void myclass(int i, int j) { a = i; b = j;} cout << ob[i].show();
void show() { cout << a << ‘ ‘ <<
b << ‘\n’; } return 0;
}; }

2
8/17/2014

Using Pointers to Objects


When a pointer to object is used, the object’s members are
referenced using the arrow (->) operator instead of the dot (.)
operator.
Pointer arithmetic using an object pointer is the same as it for any
other data type.

#include <iostream> int main() {


using namespace std; myclass ob[4] = {myclass(1, 2), myclass(3, 4),
class myclass { myclass(2, 4), myclass(4, 5)};
int a, b; myclass *p;
public:
void myclass(int i, int j) { a = i; b = j;} p = ob;
int get_a() { return a;} for( int i= 0; i < 4; i++) {
int get_b() { return b;} cout << p->get_a() << ‘ ‘;
}; cout << p->get_b() << ‘ \n’;
p++; //advance to next object
}
return 0;
}

The this Pointer


C++ contains a special pointer called this that is automatically passed to any
member function when it is called.
No C++ programmer uses the this pointer to access a class member because
the shorthand form is much easier.

#include <iostream> void inventory::show(){


#include <cstring> cout << this->item;
using namespace std; cout << “ : $” << this->cost;
cout << “ On hand: “ << this->on_hand
class inventory { << “\n”;
char item[20]; }
double cost;
int on_hand; int main() {
public: inventory ob(“wrench”, 4.95, 4);
inventory (char *i, double c, int o){
strcpy(this->item, i); ob.show();
this->cost = c; return 0;
this->on_hand = o; }
};
void show();
};

3
8/17/2014

Using new AND delete


C++ uses new operator for dynamically allocating memory (C uses malloc()).
The general form of new operator: p-var = new type;

If there is insufficient available memory, new responses varies ways-


When C++ was first invented, new returned null on failure.
Later, new causes an exception on failure.
Microsoft visual C++, returns a null pointer when new fails.
Borland C++ generates an exception when new fails.

Advantages of new:
1. Automatically allocate enough memory, no need of sizeof().
2. No explicit type cast is required.
3. Both new and delete can be overloaded.
4. It is possible to initialize the dynamically allocated memory.

General form of initializing dynamic memory:


p-var = new type (initial value);

General form of allocating 1D array:


p-var = new type [size];

Using new AND delete


C++ uses delete operator for releasing dynamically allocating memory (C
uses free()).
The general form of delete operator: delete p-var;

General form of releasing dynamically allocated array:


delete [] p-var;

#include <iostream> int main() {


using namespace std; samp *p;
class samp {
int i, j; p = new samp (6, 5);
public: if (!p){
samp(int a, int b) { i = a; j = b;}; cout << “Allocation error\n”;
int get_product() { return i*j;} return 1;
}; }
cout << “Product is: “ << p->get_product()
<< “\n”;
delete p;

return 0;
}

4
8/17/2014

Using new AND delete

Dynamic allocation of array int main() {


samp *p;

#include <iostream> p = new samp [10];


using namespace std; if (!p){
cout << “Allocation error\n”;
class samp { return 1;
int i, j; }
public: for(int i = 0; i <10; ++i){
void set_ij(int a, int b) { i = a; j = b;}; p[i].set_ij(i, 2*i);
int get_product() { return i*j;} }
};
for(int i = 0; i <10; ++i){
cout << “Product {“ << i << “] is: “;
cout << p[i].get_product() << “\n”;
}

delete [] p;

return 0;
}

References
A reference is an implicit pointer that for all intents and purposes acts like
another name for a variable.
There are three ways that a reference can be used:
A reference can be passed to a function (most important)
A reference can be returned by a function
An independent reference can be created.
Using Pointer, not Reference (only way Using References
used in C for call by reference) #include <iostream>
#include <iostream> Using namespace std;
using namespace std;
void f(int &n);
void f( int *n);
int main(){
int main(){ int i = 0;
int i = 0;
f(i);
f(&i); cout << “value of i:” << i <<’\n’;
cout << “value of i:” << i <<’\n’; return o;
return o; }
}
void f( int &n){
void f( int *n){
n = 100;
*n = 100;
}
}

5
8/17/2014

References

When a reference parameter is used, the compiler automatically passes the


address of the variable as the argument.
There is no need to manually generate the address of the argument by preceding
it with an & (in fact, it is not allowed).
Within the function, the compiler automatically uses the variable pointed to by
the reference parameter, no need to employ *.
A reference parameter fully automates the call-by-reference parameter passing
mechanism.

void f( int &n){


n = 100;
n++;
}

In the above example, instead of incrementing n, this statement increments the


value of the variable being referenced (in this case, i).

Advantages of Reference Parameters

There are several advantages of using reference parameters over their equivalent
pointer alternatives:
1. No longer need to remember to pass the address of an argument.
2. Reference parameters offer a cleaner, more elegant interface than the rather
clumsy explicit pointer mechanism.
3. When an object is passed to a function as a reference, no copy is made.

When an object is passed to a function by using call by value,


constructor is called only once and destructor is called several
times, causing serious problem.
Two solutions: to pass an object using call by reference and
using copy constructor.

6
8/17/2014

Passing References to Object

When an object is passed to a function by reference, no copy is made and


therefore its destructor function is not called when the function returns.

#include <iostream> void f(myclass &o) {


using namespace std; cout << “Received: ” << o.id() <<’\n’;
class myclass { }
int who;
public: int main(){
myclass (int n){ myclass x(1);
who = n;
cout <<”Constructing….\n”; f(x)
} return 0;
~myclass() { }
cout << “destructing…\n”;
}
int id() { return who}
};

Note that, a reference is not a pointer. Therefore, when an object is passed by


reference, the member access operator remains the dot (.), not the arrow (->).

Returning Reference
Very useful for overloading certain types of operator.
Allow a function to be used on the left side of an assignment statement.

#include <iostream>
using namespace std;
int &f();
int x; BUT
int &f(){
int main() { int x;
f() = 100; return x;
cout << x << ‘\n’; }
return 0;
}

int &f(){
return x;
}

7
8/17/2014

Independent Reference
An independent reference is a reference variable that in all effects is simply another
name for another variable.
Because reference cannot be assigned new values, an independent reference must
be initialized when it is declared.

#include <iostream> The independent reference ref


using namespace std; serves as a different name for x.
int main() {
int x; Independent reference cannot be a
int &ref = x; constant like
const int &ref = 10;
x = 10;
ref = 100;
cout << x << ” “ << ref << ’\n’;

return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy