Docsity

Object Oriented Programming by C++, Schemes and Mind Maps of Computer Programming

Toggle sidebar
bg1
34 | P a g e S R A H A T
CHAPTER 04: ARRAYS, POINTERS, AND REFERENCES
4.1 ARRAYS OF OBJECT
The syntax for declaring an array of objects is exactly like that used to declare an
array of any other type of variable.
Example:
1. This following program creates a four-element array of objects of type samp and then
loads each element's a with a value between 0 and 3.
cpp
# include <iostream >
using namespace std;
class samp
{
int a;
public :
void set_a (int n) { a = n; }
int get_a () { return a; }
};
int main ()
{
samp ob [4]; // four element array of objects
int i;
for (i=0; i <4; i++)
ob[i]. set_a (i); // loads each element's a with a value between
for (i=0; i <4; i++) 0 and 3
cout << ob[i]. get_a (); // prints all elements
cout << "\n";
return 0;
}
2. If a class type includes a constructor, an array of objects can be initialized. For
example, here ob is an initialized array:
cpp
// Initialize an array .
# include <iostream >
using namespace std;
class samp
{
int a;
public :
samp (int n) { a = n; }
int get_a () { return a; }
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download Object Oriented Programming by C++ and more Schemes and Mind Maps Computer Programming in PDF only on Docsity!

CHAPTER 04: ARRAYS, POINTERS, AND REFERENCES

4.1 ARRAYS OF OBJECT

The syntax for declaring an array of objects is exactly like that used to declare an

array of any other type of variable.

Example:

1. This following program creates a four-element array of objects of type samp and then

loads each element's a with a value between 0 and 3.

cpp

include

using namespace std; class samp { int a; public : void set_a (int n) { a = n; } int get_a () { return a; } }; int main () { samp ob [4]; // four element array of objects int i; for (i=0; i <4; i++) ob[i]. set_a (i); // loads each element's a with a value between for (i=0; i <4; i++) 0 and 3 cout << ob[i]. get_a (); // prints all elements cout << "\n"; return 0; }

2. If a class type includes a constructor, an array of objects can be initialized. For

example, here ob is an initialized array:

cpp

// Initialize an array.

include

using namespace std; class samp { int a; public : samp (int n) { a = n; } int get_a () { return a; }

int main () { samp ob [4] = { - 1, - 2, - 3, - 4 }; //initializing array while declearing int i; for (i=0; i <4; i++) cout << ob[i]. get_a () << ' '; // printing cout << "\n"; return 0; }

Actually, the syntax shown in the initialization list is shorthand for this longer form

(first shown in Chapter 2):

samp ob [4] = { samp ( - 1) , samp ( - 2) , samp ( - 3) , samp ( - 4) };

3. [Not Important] You can also have multidimensional arrays of objects. For example,

here is a program that creates a two-dimensional array of objects and initializes them:

cpp

// Create a two - dimensional array of objects.

include

using namespace std; class samp { int a; public : samp (int n) { a = n; } int get_a () { return a; } }; int main () { samp ob [4][2] = { 1, 2, 3, 4, 5, 6, 7, 8, }; int i; for (i=0; i <4; i++) { cout << ob[i ][0]. get_a () << ' '; cout << ob[i ][1]. get_a () << "\n"; } cout << "\n"; return 0; }

4.2 USING POINTERS TO OBJECT

When a pointer to an 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 is for any other data type: it is

performed relative to the type of the object. For example, when an object pointer is incremented

(p+1), it points to the next object. When an object pointer is decremented (p-1), it points to

the previous object.

Example:

1. Here is an example of object pointer arithmetic:

cpp

// Pointers to objects.

include

using namespace std; class samp { int a, b; public : samp (int n, int m) { a = n; b = m; } int get_a () { return a; } int get_b () { return b; } }; int main () { samp ob [4] = { samp (1, 2) , samp (3, 4) , samp (5, 6) , samp (7, 8) }; int i; samp *p; p = ob; // get starting address of array for (i=0; i <4; i++) { cout << p-> get_a () << ' '; cout << p-> get_b () << "\n"; p++; // advance to next object } cout << "\n"; return 0; }

Each time p is incremented (p++), it points to the next object in the array.

4.3 THE this POINTER

Clearing concept of this is very important. So, proceed to the link to ChatGPT to understand

the concept better: https://chatgpt.com/s/t_6a05e79c8624819189a0b028c9e1025e

Q. Given the following program, convert all appropriate references to class members to

explicit this pointer references.

cpp

include

using namespace std; class myclass { int a, b; public : myclass (int n, int m) { a = n; b = m; } int add () { return a+b; } void show (); }; void myclass :: show () { int t; t = add (); // call member function cout << t << "\n"; } int main () { myclass ob (10 , 14) ; ob. show (); return 0; }

Answer:

cpp

include

using namespace std; class myclass { int a, b; public : myclass (int n, int m) { this - > a = n;

Why new is better than malloc()?

  • We have to give size manually.

p = (int*) malloc (sizeof (int) );

  • No need of type cast. (int*)

Advantages of new:

1. No need of giving sizeof(int). The compiler automatically determines that,

2. No type cast (int*) needed.

3. It calls constructor automatically. malloc () has limitations here.

Myclass *p = new Myclass();

4. It calls destructor automatically.

delete p;

// Some portion skipped for now. It is more advance. If we get time, then we will discuss about

it later.

Example:

1. As a short first example, this program allocates memory to hold an integer.

cpp

// A simple example of new and delete.

include

using namespace std; int main () { int *p; p = new int; // allocate room for an integer if (!p) { cout << " Allocation error \n"; return 1; } *p = 100; cout << " Here is integer at p: " << *p << "\n"; delete p; // release memory return 0; }

Here look at the allocation of new. After allocating we have checked if p is actually

allocated the right or not. It is important because sometimes compiler give some error

while allocating memory fails. So it will now throw an exception here.

2. Here is an example that allocates an object dynamically.

cpp

// Allocating dynamic objects.

include

using namespace std; class samp { int i, j; public : void set_i (int a, int b) { i=a; j=b; } int get_product () { return i*j; } }; int main () { samp *p; p = new samp ; // allocate object if (!p) { cout << " Allocation error \n"; return 1; } p-> set_i (4, 5); cout << " Product is: " << p-> get_product () << "\n"; return 0; }

Q. Write a program that uses new to dynamically allocate a float, a long, and a char. Give

these dynamic variables values and display their values. Finally, release all dynamically

allocated memory by using delete.

Q. What are the two ways that new might indicate an allocation failure?

cout << " Here is integer at p: " << *p << "\n"; delete p; // release memory return 0; }

As you should expect, this program displays the value 9, which is the initial value given

to the memory pointed to by p.

2. The following program passes initial values to a dynamically allocated object:

cpp

// Allocating dynamic objects

include

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

When the samp object is allocated, its constructor is automatically called and is passed the

values 6 and 5.

3. The following program allocates an array of integers:

cpp

// A simple example of new and delete

include

using namespace std; int main () { int *p; p = new int [5]; // allocate room for 5 integers // always make sure that allocation succeeded

if (!p) { cout << " Allocation error \n"; return 1; } int i; for (i=0; i <5; i++) p[i] = i; for (i=0; i <5; i++) { cout << " Here is integer at p[" << i << "]: "; cout << p[i] << "\n"; } delete [] p; return 0; }

This program displays the following:

Here is integer at p[0]: 0

Here is integer at p[1]: 1

Here is integer at p[2]: 2

Here is integer at p[3]: 3

Here is integer at p[4]: 4

4. The following program creates a dynamic array of objects:

cpp

// Allocating dynamic objects.

include

using namespace std; class samp { int i, j; public : void set_ij (int a, int b) { i=a; j=b; } int get_product () { return i*j; } }; int main () { samp *p; int i; p = new samp [10]; // allocate object array if (!p) { cout << " Allocation error \n"; return 1; } for (i=0; i <10; i++) p[i]. set_ij (i, i);

for (i=0; i <10; i++) { cout << " Product [" << i << "] is: "; cout << p[i]. get_product () << "\n"; } delete [] p; return 0; }

This program displays the following:

Here is integer at p[0]: 0

Product [0] is: 0

Product [1] is: 1

Product [2] is: 4

Product [3] is: 9

Product [4] is: 16

Product [5] is: 25

Product [6] is: 36

Product [7] is: 49

Product [8] is: 64

Product [9] is: 81

Destroying...

Destroying...

Destroying...

Destroying...

Destroying...

Destroying...

Destroying...

Destroying...

Destroying...

Destroying...

As you can see, samp's destructor is called ten times- once for each element in the array.

Q. Show how to convert the following code into its equivalent that uses new.

cpp

char *p; p = ( char *) malloc (100) ; // ... strcpy (p, " This is a test ");

Solution:

include

include // for strcpy

using namespace std ; int main() {

char *p; p = new char[100]; // allocate memory using new // ... strcpy(p, "This is a test"); cout << p << endl; // Optional: print to verify delete[] p; // don't forget to free memory return 0; } 4.6 REFERENCES

To help you understand what a reference parameter is and how it works, let's first start with a

program that uses a pointer (not a reference) as a parameter:

cpp

include

using namespace std; void f(int *n); // use a pointer parameter int main () { int i = 0; f(&i); cout << " Here is i's new value : " << i << "\n"; return 0; } void f(int *n) { *n = 100; // put 100 into the argument pointed to by n }

Here f() loads the value 100 into the integer pointed to by n. In this program, f() is called with

the address of i in main(). Thus, after f() returns, i contains the value 100.

However, in C++, you can completely automate this process by using a reference parameter.

To see how, let's rework the previous program. Here is a version that uses a reference parameter:

cpp

include

using namespace std; void f(int &n); // declare a reference parameter int main () {

Example:

1. The classic example of passing arguments by reference is a function that exchanges the

values of the two arguments with which it is called. Here is an example called

swapargs() that uses references to swap its two integer arguments:

cpp

include

using namespace std; void swapargs (int &x, int &y) { int t; t = x; x = y; y = t; } int main () { int i, j; i = 10; j = 19; cout << "i: " << i << ", "; cout << "j: " << j << "\n"; swapargs (i, j); cout << " After swapping : "; cout << "i: " << i << ", "; cout << "j: " << j << "\n"; return 0; }

If swapargs() had been written using pointers instead of references, it would have

looked like this:

cpp

void swapargs (int *x, int *y) { int t; t = *x; *x = *y; *y = t; }

2. Here is a program that uses the round() function to round a double value. The value to

be rounded is passed by reference.

cpp

include

include

using namespace std; void round ( double &num );

int main () { double i = 100.4; cout << i << " rounded is "; round (i); cout << i << "\n"; i = 10.9; cout << i << " rounded is "; round (i); cout << i << "\n"; return 0; } void round ( double &num ) { double frac ; double val; frac = modf (num , &val ); /* modf() function is a pre-built function of header file if( frac < 0.5) it separates fraction and integer part from any number num =val ; modf() returns a fraction value, so we keep it in frac else the integer part is kept in val. */ num = val +1.0; // syntex: modf (number, &integer_part) }

Q. Question from Previous Year

Hint: Go-to page 48. Here the concept will help you to solve the problem. Look at the syntex

carefully.

int main () { myclass x(1) ; f(x); return 0; }

This function displays the following:

Constructing 1

Received 1

Destructing 1 // This is for copy of the object

Destructing 1 // This is for the termination of the code and main object

As you can see, the destructor function is called twice - first when the copy of object 1 is

destroyed when f() terminates and again when the program finishes.

However, if the program is changed so that f() uses a reference parameter, no copy is made

and, therefore, no destructor is called when f() returns:

cpp

include

using namespace std; class myclass { int who ; public : myclass (int n) { who = n; cout << " Constructing " << who << "\n"; } ~ myclass () { cout << " Destructing " << who << "\n"; } int id () { return who; } }; // Now o is passed by reference. void f( myclass &o) { // note that. operator is still used !! cout << " Received " << o.id () << "\n"; }

int main () { myclass x(1) ; f(x); return 0; }

This version displays the following output:

Constructing 1

Received 1

Destructing 1

Remember: When accessing members of an object by using a reference, use the dot operator,

not the arrow.

Q. What is wrong with the following program? Show how it can be fixed by using a

reference parameter. Justify your answer.

cpp

// This program has an error.

include

include

include

using namespace std; class strtype { char *p; public : strtype ( char *s); ~ strtype () { delete [] p; } char *get () { return p; } }; strtype :: strtype ( char *s) { int l; l = strlen (s)+1; p = new char [l]; if (!p) { cout << " Allocation error \n"; exit (1) ; } strcpy (p, s); }