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

Unit 3 Lec Notes

The document discusses pointers in C++. Pointers hold the memory address of another variable. Pointer variables must be declared with a data type and asterisk. The ampersand operator returns the address of a variable. Pointers allow passing variables as arguments and returning structured variables from functions.

Uploaded by

algebra5317
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)
19 views

Unit 3 Lec Notes

The document discusses pointers in C++. Pointers hold the memory address of another variable. Pointer variables must be declared with a data type and asterisk. The ampersand operator returns the address of a variable. Pointers allow passing variables as arguments and returning structured variables from functions.

Uploaded by

algebra5317
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/ 50

Pointers

1 INTRODUCTION
It is well known that pointer data type is somewhat difficult to understand by the novice programmers but
it is one of the strengths of the C++ language. The pointer is a powerful technique to access the data by
indirect reference as it holds the address of that variable where it has been stored in the memory.

1.1 Pointer Declaration


A pointer is a variable which holds the memory address of another variable. Sometimes, only with the
pointer a complex data type can be declared and accessed easily. The pointer has the following advantages:
∑ It allows to pass variables, arrays, functions, strings and structures as function arguments.
∑ A pointer allows to return structured variables from functions.
∑ It provides functions which can modify their calling arguments.
∑ It supports dynamic allocation and deallocation of memory segments.
∑ With the help of a pointer, variables can be swapped without physically moving them.
∑ It allows to establish links between data elements or objects for some complex data structures such as
linked lists, stacks, queues, binary trees, tries and graphs.
∑ A pointer improves the efficiency of certain routines.
A pointer contains a memory address. Most commonly, this address is the location of another variable
where it has been stored in memory. If one variable contains the address of another variable, then the first
variable is said to point to the second. In C++, pointers are distinct such as integer pointer, floating point
number pointer, character pointer, etc. A pointer variable consists of two parts, namely, (i) the pointer
operator, and (ii) the address operator.

1.2 Pointer Operator


A pointer operator can be represented by a combination of * (asterisk) with a variable. For example, if a
variable of integer data type and also declared * (asterisk) with another variable, it means the variable is of
type “pointer to integer”. In other words, it will be used in the program indirectly to access the value of one
or more integer variables.
The general format of the pointer declaration is given below:
data_type *pointer_variable;
where data_type is a type of pointer variable such as integer, character and floating point number,
structs, arrays, etc. and the pointer_variable is any valid C++ identifier. Note that the asterisk must
be preceded by the pointer variable.
For example,
int *ptr;
where ptr is a pointer variable which holds the address of
an integer data type. The internal representation of ptr is
shown in the following Fig. 8.1.
All pointer variables must be declared before it is used in
C++ programs like other variables. When a pointer variable Fig.1 Memory Address of a variable x
is declared, the variable name must be preceded by an
asterisk (*). This identifies the variable as a pointer.
Following are valid pointer declarations.
float *fpointer;
double *dpoint;
char *mpoint1;
The base type of the pointer indicates the type of variable the pointer is pointing to. Technically, any
type of pointer can point to anywhere in the memory. All pointer arithmetic is done relative to its base type.
Hence, it is important to declare pointers correctly. For example, a character data item may require to store
only a byte (8 bits); an integer may require to store two bytes (16 bits); a floating point number may require
four bytes (32 bits), a double precision number may require eight bytes (64 bits). The number of bytes
required to store a particular data items varies from machine to machine.

1.3 Address Operator


An address operator can be represented by a combination of & (ampersand) with a pointer variable. For
example, if a pointer variable is an integer type and also declared & with the pointer variable, then it means
that the variable is of type “address of”. In other words, it will be used in the program to indirectly access
the value of one or more integer variables.
The & is a unary operator that returns the memory address of its operand. A unary operator requires only
one operand.
For example,
m = &ptr;
Note that the pointer operator & is an operator that returns the address of the variable following it.
Therefore, the preceding assignment statement could be verbalised as “m receives the address of ptr”.
The other operator * is the complement of &. It is a unary operator that returns the value of the variable
located at the address that follows.
The operation of * translates to the phrase “at address”. Note that the symbol * represents both the
multiplication sign and the “at address”, and the symbol & represents both bitwise AND and the “address
of” sign. When these are used as pointer operators, they have no relationship to the arithmetic operators
that happen to look like the same. Both the pointer operators, & and *, have a higher precedence over all
other arithmetic operators except the unary minus, with which they have equal precedence.
The pointer and address operators & and * are the members of the same precedence group as the
other unary operators such as -, ++, --,!, sizeof and cast operator. Note that the group unary
operators have higher precedence over the group of arithmetic operators, and the associatives of the unary
operators are from left to right.

1.4 Pointer Expressions


(a) Pointer Assignment A pointer is a variable data type and hence the general rule to assign its value to the
pointer is same as that of any other variable data type. For example,
int x,y;
int *ptr1,*ptr2;
(1)
ptr1 = &x;
The memory address of variable x is assigned to the pointer variable ptr1.
(2)
y = *ptr1;
The contents of the pointer variable ptr1 is assigned to the variable y, not the memory address.
(3)
ptr1 = &x;
ptr2 = ptr1; // address of ptr1 is assigned to ptr2
The address of the ptr1 is assgined to the pointer variable ptr2. The contents of both ptr1 and
ptr2 will be the same as these two pointer variables hold the same address. The following Fig. 2
shows how an address of ptr1 is assigned to ptr2.

Fig. 2 Address of ptr1 is assigned to ptr2


Some invalid pointer declaration
(1)
int x;
int x_pointer;
x_pointer = &x;
Error: pointer declaration must have the prefix of * (unary operator).
(2)
float y;
float *y_pointer;
y_pointer = y;
Error: While assigning variable to the pointer variable the address operator (&) must be used along
with the variable y.
(3)
int x;
char *c_pointer;
c_pointer = &x;
Error: Mixed data type is not permitted.
(b) Finding the Address of an Object As we described earlier, every variable has a unique address that
identifies its storage location in memory. For some applications, it is useful to access the variable through
its address rather than through its name. To obtain the address of a variable, programmer has to use the
ampersand (&) operator.
Suppose, for instance, that j is the long int whose address is 248600, the statement,
ptr = &j;
stores the address value 248600 in the variable ptr. When reading an expression, the ampersand operator
is translated as “address of”. One would read this statement as: “ Assign the address of j
to the ptr”. The following program points the value of the variable called j and the address of j:
#include <iostream.h>

int main()
{
int j = 100;
cout <<“ value of j = ” << j << endl;
cout <<“ address of j = ” << &j << endl;
return 0;
}
Output of the above program
value of j = 100
address of j = 0x1ab4fff2
The address represents the actual location of j in memory. The particular address listed above
is arbitrary. Note that one cannot use the ampersand operator on the left hand side of an assignment
expression. For instance, the following is illegal since one cannot change the address of an object:
&ptr = 1000; // error

(c) Initialising Pointers One can initialise a pointer variable just like any other type of variable in a program.
However, the initialisation value must be an address. The following pointer declaration is valid
int j;
int *ptr = &j;
However, one cannot reference a variable before it is declared, so the following declarations would be
illegal:
int *ptr = &j;
int j; // error

(d) The NULL Pointer The C++ language supports the notion of a null pointer. A null pointer is a method
or approach in which a pointer variable is guaranteed not to point to a valid object. In other words, a null
pointer is any pointer assigned the integral value zero.
For example,
char *ptr;
ptr = 0; // make ptr a null pointer
Another form of using the null pointer is given below:
ptr = NULL;
NULL is a built-in constant for assigning the integral value zero.
Null pointers are particularly useful in control flow statements since the zero valued pointer evaluates to
false, whereas all other pointer values evaluates to true. For example, the following while loop continues
iterating while ptr is null pointer.
char *ptr;
-------
-------
while (ptr) {
-------
-------
} // iterate until ptr is a null pointer
This use of null pointers is particularly prevalent in applications that are arrays of pointers.

PROGRAM 1
A program to assign an address of an integer variable to the pointer variable and display the content of
and address of the pointer.
#include <iostream.h>
int main()
{
int x;
int *ptr;
x = 10;
ptr = &x;
cout << “ x = ” << x <<“ and ptr = ” << ptr;
cout << endl;
cout << “ x = ” << x << “ and *ptr = ” << *ptr;
cout << endl;
return 0;
}
Output of the above program
x = 10 and ptr = 0xbfffe7d4
x = 10 and *ptr = 10
In the above program, x is an integer variable and ptr is declared as the pointer to an integer. Initially,
value 10 is assigned to the integer variable x. The address of the variable x is assigned to the ptr.
ptr = &x //address of x is assigned to the variable ptr
*ptr = &x //content of x is assigned to the *ptr

PROGRAM 2
A program to assign a character variable to the pointer and display the content of the pointer.
#include <iostream.h>

int main()
{
char x,y;
char *pointer;
x = ‘c’; // assign character
pointer = &x;
y = *pointer;
cout << “ value of x = ” << x;
cout << endl;
cout << “ pointer value = ” << y;
cout << endl;
return 0;
}
Output of the above program
value of x = c
pointer value = c

PROGRAM 3
A program to display the address and the content of a pointer variable.
#include <iostream>
using namespace std;
int main()
{
int x;
int *ptr;
x = 10;
ptr = &x;
cout << “value of x = ”<< x << ‘\n’;
cout << “contents of ptr = ” << *ptr << ‘\n’;
cout << “Address of ptr = ” << ptr << ‘\n’;
return 0;
}
Output of the above program
value of x = 10
contents of ptr = 10
Address of ptr = 0xbffff654

PROGRAM 4

A program to assign the pointer variable to another pointer and display the contents of both the pointer variables.
#include <iostream.h>
int main()
{
int x;
int *ptr1,*ptr2;
x = 10;
ptr1 = &x;
ptr2 = ptr1;
cout << “value of x = ” << x << ‘\n’;
cout << “Contents of ptr1 = ” << *ptr1 << ‘\n’;
cout << “Contents of ptr2 = ” << *ptr2 << ‘\n’;
return 0;
}
Output of the above program
value of x = 10
Contents of ptr1 = 10
Contents of ptr2 = 10

2 POINTER ARITHMETIC
As a pointer holds the memory address of a variable, some arithmetic operations can be performed with
pointers. C++ supports four arithmetic operators that can be used with pointers, such as
Addition +
Subtraction -
Incrementation ++
Decrementation --
Pointers are variables. They are not integers, but they can be displayed as unsigned integers. The
conversion specifier for a pointer is added and subtracted. For example,
ptr++ causes the pointer to be incremented, but not by 1.
ptr-- causes the pointer to be decremented, but not by 1.
The following program segment illustrates the pointer arithmetic.
The integer value would occupy bytes 2000 and 2001
int value , *ptr;
value = 120;
ptr = &value;
ptr++;
cout << ptr;
The above C++ program segment displays 2002.
Figure 3(a) shows how a pointer arithmetic is carried out for an int data type.

Fig. 3(a) Pointer Arithmetic

The pointer ptr is originally assigned the value 2000. The incrementation, ptr++, increments the
number of bytes of the storage class for the particular machine. If the system used four bytes to store an
integer, then ptr++ would have resulted in ptr being equal to 2004.
The general rule for pointer arithmetic is that pointer performs the operation in bytes of the appropriate
storage class. Figure 3(b) illustrates how a pointer arithmetic is performed for a floating point data type.

Fig. 3(b) Pointer Arithmetic

PROGRAM 5
A program to display the memory address of a variable using pointer before incrementation and after
incrementation.
// pointer arithmetic
#include <iostream.h>
#include <iomanip.h>
int main()
{
int value ;
int *ptr;
value = 120;
ptr = &value;
cout << “Memory address before incrementation = ” << ptr;
cout << endl;
ptr++;
cout << “Memory address after incrementation = ” << ptr;
cout << endl;
return 0;
}
Output of the above program
Memory address before incrementation = 0xbfffe7d4
Memory address after incrementation = 0xbfffe7d8

PROGRAM 6

A program to display the memory address of a variable using pointer before decrementation and after
decrementation.
// pointer arithmetic
#include <iostream.h>
int main()
{
float value ;
float *ptr;
value = 120.00;
ptr = &value;
cout << “Memory address = ” << ptr <<endl;
ptr—–;
cout << “Memory address after decrementer = ” << ptr << endl;
return 0;
}
Output of the above program
Memory address = 0xbffff8d4
Memory address after decrementer = 0xbffff8d0
Each time a pointer is incremennted, it points to the memory location of the next element with its base
type. Each time it is decremented, it points to the location of the previous element. In the case of pointers
to characters, this often produces what appears to be “normal” arithmetic. However, all other pointers
increase or decrease the length of the data type they point to.
For example, assume 1 byte characters and 2 byte integers. When a character pointer is incremented, its
value increases by 1. However, when an integer pointer is incremented, its value increases by 2. The reason
for this is that each time a pointer is incremented or decremented, it is incremented or decremented relative
to its length of its base type so that it always points to the next element.
All pointer arithmetic are done relative to the base type of the pointer so that the pointer is always
pointing to the appropriate element of the base type. The pointers are not limited to only incrementing or
decrementing. A pointer variable may be added or subtracted to or from integers. For example,
ptr = ptr +9 ;
makes ptr to point to the ninth element of ptr type beyond the element it currently points to.

PROGRAM 7

A program to display the memory address of a variable using a pointer; add an integer quantity with the
pointer and to display the contents of the pointer.
// pointer arithmetic
#include <iostream.h>
int main()
{
int x;
int *ptr1,*ptr2;
x = 10;
ptr1 = &x;
ptr2 = ptr1+6;
cout << “\n value of x = ” << x;
cout << “\n Contents of ptr1 = ” << *ptr1;
cout << “\n Address of ptr1 = ” << ptr1;
cout << “\n Address of ptr2 = (ptr1+6) = ” << ptr2;
cout << “\n Contents of ptr2 = ” << *ptr2;
return 0;
}
Output of the above program
value of x = 10
Contents of ptr1 = 10
Address of ptr1 = 0xbffff1d4
Address of ptr2 = (ptr1+6) = 0xbffff1ec
Contents of ptr2 = 1073829932 (garbage value)
The memory address of the pointer variable ptr1 is 0xbffff1d4 and an integer value 6 is added with
a pointer ptr2. For one integer, the pointer variable takes 4 bytes to store, then, the resultant address value
is 0xbffff1ec. The content of the pointer is a garbage data.
No other arithmetic operations are allowed other than addition and subtraction with pointers on integers.
To be specific, pointers are not permitted to perform the following arithmetic operations.
(i) To multiply or divide,
(ii) To operate the bitwise shift and mask operations, and
(iii) To add or subtract type float or type double to pointers.

PROGRAM 8

A program to display the address and content of a pointer variable; subtract with an integer quantity and
to display the address of and the contents the pointer variable.
// pointer arithmetic
#include <iostream.h>
int main()
{
int x;
int *ptr1,*ptr2;
x = 10;
ptr1 = &x;
ptr2 = ptr1-2;
cout << “value of x =” << x <<endl;
cout << “Contents of ptr1 = ” << *ptr1 <<endl;
cout << “Address of ptr1 =” << ptr1<<endl;
cout << “Address of ptr2 = (ptr1-2) =” << ptr2 << endl;
cout << “Contents of ptr2 =” << *ptr2 <<endl;
return 0;
}
Output of the above program
value of x =10
Contents of ptr1 = 10
Address of ptr1 =0xbfffed54
Address of ptr2 = (ptr1-2) =0xbfffed4c
Contents of ptr2 =-1073746612

PROGRAM 9
A program to display the contents of the pointer variables using arithmetic operation.
// pointer arithmetic
#include <iostream.h>
int main()
{
int x,y;
int *ptr;
x = 10;
ptr = &x;
cout << “\n value of x =” << x << “ and pointer =” << *ptr;
y = *ptr +1;
cout << “\n value of y =” << y << “ and pointer =” << *ptr;
return 0;
}
Output of the above program
value of x =10 and pointer =10
value of y =11 and pointer =10

PROGRAM 10
A program to display the contents of a pointer variable before and after incrementation.
//pointer arithmetic
#include <iostream.h>
int main()
{
int x,y;
int *ptr;
x = 10;
ptr = &x;
cout << “\n value of x =” << x <<“ and pointer =” << *ptr;
y = ++ *ptr;
cout << “\n value of y =” << y <<“ and pointer =” << *ptr;
cout << ‘\n’;
return 0;
}
Output of the above program
value of x = 10 and pointer = 10
value of y = 11 and pointer = 11

PROGRAM 11

A program to display the contents and the address of a pointer variable using different types of incrementation.
//pointer arithmetic
#include <iostream.h>
int main()
{
int x,y;
int *ptr, *ptr2;
x = 10;
ptr = &x;
cout << “content of pointer =”<<*ptr<<endl;
*ptr = *ptr +1; // (*ptr++)
y = *ptr;
cout << “value of y =” << y << ‘\t’;
cout << “and pointer *ptr = *ptr +1 =” << *ptr<<endl;
*ptr += 1; // (*ptr++)
y = *ptr;
cout << “value of y = ” << y << ‘\t’;
cout << “and pointer *ptr += 1 =” << *ptr<<endl;
(*ptr)++; // parentheses are necessary
y = *ptr;
cout << “value of y = ” << y << ‘\t’;
cout << “ and pointer (*ptr)++ =” << *ptr<<endl;
++ *ptr;
y = *ptr;
cout << “value of y =” << y << ‘\t’;
cout << “and pointer (++ *ptr) =” << *ptr<<endl;
++ *ptr;
ptr2 = ptr;
cout << “pointer1 = ” << *ptr << ‘\t’;
cout << “and pointer2 =” << *ptr2 <<endl;
return 0;
}
Output of the above program
content of pointer = 10
value of y = 11 and pointer *ptr = *ptr + 1 = 11
value of y = 12 and pointer *ptr + = 1 = 12
value of y = 13 and pointer (*ptr)++ = 13
value of y = 14 and pointer (++ *ptr) = 14
pointer1 = 15 and pointer2 = 15

PROGRAM 12

A program to display the content of a pointer variable using an ordinary and pointer arithmetic.
// pointer arithmetic
#include <iostream.h>
int main()
{
int x,y;
int *xpointer;
int temp;
temp = 3;
x = 5* (temp+5);
xpointer = &temp;
y = 5* (*xpointer+5);
cout << “x = ” << x <<endl;
cout << “y = ” << y <<endl;
return 0;
}
Output of the above program
x = 40
y = 40
The above program consists of two expressions — one, an ordinary arithmetic expression and the other
a pointer expression.
x = 5 * (temp +5)
where temp = 3
x = 5 *(3 + 5)
= 5 * (8)
= 40
Using the pointer arithmetic,
xpointer = &temp;
where temp = 3;
y = 5 * (*xpointer + 5)
= 5 * (3 + 5)
= 5 * 8 = 40
2.1 Summary of Pointer Arithmetic

Pointer arithmetic description


ptr++ ptr = ptr+sizeof(data_type)
use original value of ptr and then ptr is incremented after statement execution
++ptr ptr = ptr+sizeof( data_type)
original ptr is incremented before execution of statement
ptr-- ptr = ptr-sizeof(data_type)
use original value of ptr and then ptr is decremented after statement execution
--ptr ptr = ptr-sizeof( data_type)
original ptr is decremented before the execution of statement
*ptr++ *(ptr++)
retrieve the content of the location pointed to by pointer and then increment ptr
* ++ptr *(++ptr)
increment pointer and then retrieve the content of the new location pointed to by ptr
(*ptr)++ increment content of the location pointed to by ptr. For pointer type content, use pointer
arithmetic else use standard arithmetic
++ *ptr ++ (*ptr)
increment the content of the location pointed to by ptr depending on the type of the content
-- *ptr -- (*ptr)
decrement content of the location pointed to by ptr depending on the type of the content
*ptr-- *(ptr--)
retrieve the content of the location pointed to by ptr and then decrement ptr
* --ptr *(--ptr)
decrement ptr, then retrieve the content of the new location pointed to by ptr
(*ptr)-- retrieve content *ptr of the location pointed to by ptr, then decrement the content of that
location; ptr is not changed
POINTERS AND CLASSES

A pointer is a variable which holds the memory address of another variable of any basic data
types such as int, flfloat or sometimes an array.
It has also been illustrated how a pointer can be used to hold the address of a structure variable too.
The pointer variable is very much used to construct complex data bases using the
data structures such as linked lists, double linked lists and binary trees.
So far, it has been shown that a data member and a member function of a class could be an ordinary data
type such as int, flfloat, char and even a class also. In this section, how a pointer variable can be declared as
a
member to a class is discussed.
The following declaration of creating an object is valid in C++.
class sample {
private :
int x;
flfloat y;
char s;
public :
void getdata();
void display();
};
sample *ptr;
where ptr is a pointer variable that holds the address of the class object sample and consists of the three
data members such as int x, flfloat y and char s, and also holds member functions such as getdata()
and
display().
The pointer to an object of class variable will be accessed and processed in one of the following ways,
(*object name).member name = variable;
The parentheses are essential since the member of class period (.) has a higher precedence over the
indirection operator (*). Or, the pointer to the member of a class can be expressed using dash (–) followed
by the greater than sign (>). object name -> member name = variable;
Case 1 A member of class object can be accessed by the indirection operator which has been shown in the
Following are valid declarations of using pointer to the member of a class.
following program segment:
class student {
private :
-------
-------
public :
-------
-------
}; // end of class definition

void main(void)
{
student *ptr;
-------
-------
(*ptr).data_member;
(*ptr).member_function();
}

Case 2 A member of class object can be accessed by the pointer of a class operator which has been shown
in the following program segment:
class student {
private :
-------
-------
public :
-------
-------
}; // end of class de nition

int main()
{
student *ptr;
-------
-------
ptr->data_member;
ptr->member_function();
return 0;
}

PROGRAM 1
A program to assign some values to the member of class objects using a pointer structure operator (–>).
// pointers and classes 1.cpp
#include <iostream.h>
class student_info {
private :
long int rollno;
int age;
char sex;
float height;
float weight;
public :
void getinfo ();
void disinfo ();
}; // end of class de nition
void student_info :: getinfo()
{
cout << “ Roll no :”;
cin >> rollno;
cout <<“ Age :”;
cin >> age;
cout << “ Sex : ”;
cin >> sex;
cout << “ Height : ”;
cin >> height;
cout << “ Weight : ”;
cin >> weight;
}
void student_info :: disinfo()
{
cout << endl;
cout << “ Roll no = ” << rollno << endl;
cout << “ Age = ” << age << endl;
cout << “ Sex = ” << sex << endl;
cout << “ Height = ” << height << endl;
cout << “ Weight = ” << weight << endl;
}
int main()
{
student_info *ptr; // ptr is an object of class student
cout << “ enter the following information ” << endl;
ptr->getinfo();
cout << “ \n contents of class ” << endl;
ptr->disinfo();
return 0;
}

Output of the above program


enter the following information
Roll no : 200710
Age : 23
Sex : M
Height : 176
Weight: 67

contents of class
Roll no = 200710
Age = 23
Sex = M
Height = 176
Weight = 67

PROGRAM 2
A program to assign some values to the member of class objects using an indirection operator.
// pointers and classes 2.cpp
#include <iostream.h>
class student_info {
private :
long int rollno;
int age;
char sex;
oat height;
oat weight;
public :
void getinfo();
void disinfo();
}; // end of class de nition
void student_info :: getinfo()
{
cout << “ Roll no :”;
cin >> rollno;
cout <<“ Age :”;
cin >> age;
cout << “ Sex : ”;
cin >> sex;
cout << “ Height : ”;
cin >> height;
cout << “ Weight : ”;
cin >> weight;
}
void student_info :: disinfo()
{
cout << endl;
cout << “ Roll no = ” << rollno << endl;
cout << “ Age = ” << age << endl;
cout << “ Sex = ” << sex << endl;
cout << “ Height = ” << height << endl;
cout << “ Weight = ” << weight << endl;
}
int main()
{
student_info *ptr; // ptr is an object of class student
cout << “ enter the following information ” << endl;
(*ptr).getinfo();
cout << “ \n contents of class ” << endl;
(*ptr).disinfo();
return 0;
}
Output of the above program
enter the following information
Roll no : 200711
Age : 22
Sex : F
Height : 156
Weight : 71

contents of class
Roll no = 200711
Age = 22
Sex = F
Height = 156
Weight = 71

PROGRAM 3

A program to find the distance between the given two points using the pointer to class objects technique.
// classes and pointers
#include <iostream.h>
#include <cmath>
class point {
private :
int x,y;
public :
point (int xnew,int ynew);
inline int getx() {
return(x);
}
inline int gety() {
return(y);
}
float nddi st(po int a, poin t b);
}; // end of class de nition
point :: point (int xnew, int ynew)
{
x = xnew;
y = ynew;
}
oat point :: nddist (point a, point b)
{
float temp;
temp = ((b.y-a.y)*(b.y-a.y)) + ((b.x-a.x)*(b.x-a.x));
return (sqrt(temp));
}
int main()
{
point aobj(4,3),bobj(0,-1);
point *aptr = &aobj;
point *bptr = &bobj;
aptr->getx();
aptr->gety();
bptr->getx();
bptr->gety();
oat value;
value = aptr-> nddist(aobj,bobj);
cout << “ distance between two points =” << value << endl;
return 0;
}
Output of the above program
distance between two points = 5.65685
DYNAMIC MEMORY ALLOCATIONS

Two operators, namely, new and delete are used in dynamic memory allocations which are described in
detail in this section.
(a) New The new operator is used to create a heap memory space for an object of a class. In C, there
are special functions used to create a memory space dynamically, viz. malloc(), calloc() and
alloc(). C++ provides a new way in which dynamic memory is allocated. In reality, the new keyword
calls upon the function operator new() to obtain storage.
Basically, an allocation expression must carry out the following three things:
(i) Find storage for the object to be created,
(ii) Initialise that object, and
(iii) Return a suitable pointer type to the object.
The new operator returns a pointer to the object created. Functions cannot be allocated this way using
new operator but pointers to functions can be used for allocating memory space.
The general syntax of the new operator is,
data_type pointer = new data_type;
where data_type can be a short integer, flfloat, char, array or even class objects.
For example,
new int; // an expression to allocate a single integer
new // an expression to allocate a flfloating
flfloat; value
If the call to the new operator is successful, it returns a pointer to the space that is allocated. Otherwise it
returns the address zero if the space could not be found or if some kind of error is detected.
(b) Delete The delete operator is used to destroy the variable space which has been created by using the
new operator dynamically. It is analogous to the function free() in C. In reality, the delete keyword calls
upon the function operator delete() to release storage which was created using the new operator.
The general syntax of the delete operator is:
delete pointer ;
As the new operator returns a pointer to the object being created, the delete operator must define a only
pointer name but not with data type. The delete operator takes no arguments for deleting a single instance
of a memory variable created by a new operator.
For example,
char *ptr_ch = new char; // memory for a character is allocated
int *ptr_i = new int; // memory for an integer is allocated
delete ptr_ch; // delete memory space
delete ptr_i; // delete
Note that the delete operator is used for only releasing the heap memory space which was allocated by
the new operator. If attempts are made to release memory space using delete operator that was not allocated
by the new operator, then it gives unpredictable results. The following usage of the delete operator is
invalid, as the delete operator should not be used twice to destroy the same pointer.
char *ptr_ch = new char; // allocating space for a character
delete ptr_ch;
delete ptr_ch; // error
PROGRAM 4

A program to create a dynamic memory allocation for the standard data types: integer, fl floating
point,
character and double. The pointer variables are initialised with some data and the contents of the pointers
are displayed on the screen.
//using new and delete operators
#include <iostream.h>

int main()
{
int *ptr_i = new int (25);
float *ptr_f = new float(-10.1234F);
char *ptr_c = new char(‘a’);
double *ptr_d = new double (1234.5667L);
cout << “contents of the pointers “ << endl;
cout << “integer = “ << *ptr_i << endl;
cout << “floafloatng point value = “ << *ptr_f << endl;
cout << “char = “ << *ptr_c << endl;
cout << “double = “ << *ptr_d << endl;
delete ptr_i;
delete ptr_f;
delete ptr_c;
delete ptr_d;
return 0;
}
Output of the above program
contents of the pointers
integer = 25
oating point value = -10.1234
char = a
double = 1234.57

PROGRAM 5
A program to read two integers from the keyboard and perform simple arithmetic operations using the
pointer technique. The memory space for the variables are allocated by the new operator.
//using new and delete operators
#include <iostream.h>
int main()
{
int *ptr_a = new int;
int *ptr_b = new int;
int *ptr_sum = new int;
int *ptr_sub = new int;
int *ptr_mult = new int;
oat *ptr_div = new oat;
cout << “ enter any two integers \n”;
cin >> *ptr_a >> *ptr_b;
*ptr_sum = *ptr_a + *ptr_b;
*ptr_sub = *ptr_a - *ptr_b;
*ptr_mult = *ptr_a * *ptr_b;
*ptr_div = ( ofloat)*ptr_a / ( float)*ptr_b;
cout << “ Addition of (*ptr_a + *ptr_b) = “ << *ptr_sum;
cout << endl;
cout << “ Subtraction of (*ptr_a - *ptr_b) = “ << *ptr_sub;
cout << endl;
cout << “ Multiplication of (*ptr_a * *ptr_b) = “ << *ptr_mult;
cout << endl;
cout << “ Division of (*ptr_a / *ptr_b) = “ << *ptr_div;
cout << endl;
delete ptr_a;
delete ptr_b;
delete ptr_sum;
delete ptr_sub;
delete ptr_mult;
delete ptr_div;
return 0;
}
Output of the above program
enter any two integers
1 2
Addition of (*ptr_a + *ptr_b) = 3
Subtraction of (*ptr_a - *ptr_b) = -1
Multiplication of (*ptr_a * *ptr_b) = 2
Division of (*ptr_a / *ptr_b) = 0.5

(c) Array Data Type When an object is an array data type, a pointer to its initial element is returned.
new int;
new int[20];
Both the expressions return a pointer to the first element of the array as
int *;
The general syntax of the new operator for the array data type is,
data_type pointer = new data_type[size];
where data_type can be a short integer, float, char, array or even class objects, and
size is the maximum number of elements that are to be accommodated.
For example,
(1) An expression to allocate a memory space for 20 integers using new operator.
int *ptr_a = new int[20];
(2) An expression to create memory space for 100 characters using new operator.
char *ptr_ch = new char[100];

(d) Use of New Operator to Allocate Memory for a Two-Dimensional Array A two-dimensional array can be
declared using the new operator as,
new int [10][20];
which returns
int (*)[20];
The general syntax of the new operator for the two-dimensional array data type is,
data_type (pointer)[size] = new data_type[size][size];
where data_type can be a short integer, float, char, array or even class objects and
size is the maximum number of elements that are to be accommodated.
For example,
(1) An expression to allocate memory space for of 5×5 integers using new operator.
int (*ptr_a)[5] = new int [5][5];
(2) An expression to create memory space for 10×10 characters using new operator.
int (*ptr_c)[10] = new int [10][10];
The following section shows how the delete operator is used to destroy the objects created by the new
operator for the array data type. The expression for the delete operator is same for both the one-dimensional
and multidimensional arrays.
The general syntax of the delete operator for an array data type is,
delete [] ptr_a; //delete an array of pointer ptr_a;
For example, the following program segment shows how to use the delete operator in a one-dimensional
array.
int main()
{
char *ptr_ch = new char[100];
oat *ptr_f = new oat [20];
-------
-------
delete [] ptr_ch;
delete [] ptr_f;
}
For example, the following program segment shows how to use the delete operator in a two-dimensional
array.
int main()
{
int (*ptr_c)[10] = new int [10][10];
oat (*ptr_f)[20] = new oat [20][20];
-------
-------
delete [] ptr_c;
delete [] ptr_f;
}

PROGRAM 11.34
A program to allocate contiguous memory space for an array of integers using the new operator and the
object of the array is destroyed by the delete operator. This program reads a set of numbers from the
keyboard and displays it on the screen.
//using new and delete operators for array data type
#include <iostream.h>
int main()
{
int *ptr_a = new int[20];
int *ptr_n = new int;
cout << “ how many numbers are there ? \n”;
cin >> *ptr_n;
for ( int i = 0; i<= *ptr_n -1; ++i) {
cout << “ element a[“ << i <<“] = “;
cin >> ptr_a[i];
}
cout << “ contents of the array \n”;
for (int i = 0; i<= *ptr_n -1; ++i) {
cout << ptr_a[i] ;
cout << ‘\t’;
}
delete ptr_n;
delete [] ptr_a;
return 0;
}
Output of the above program
how many numbers are there?
5
element a[0] = 11
element a[1] = 22
element a[2] = 33
element a[3] = 44
element a[4] = 55

contents of the array


11 22 33 44 55

PROGRAM 6

This program demonstrates how memory is allocated for a multidimensional array of data elements using
the new operator and destroying it using the delete operator. A program to read a two-dimensional matrices
A and B; perform the matrix addition of these matrices and display the added elements on the screen.
//using new and delete operators for two dimensional
//array data type
#include <iostream.h>
#include <iomanip.h>
int main()
{
int (*ptr_a)[5] = new int [5][5];
int (*ptr_b)[5] = new int [5][5];
int (*ptr_c)[5] = new int [5][5];
int *ptr_n = new int;
cout << “ order of the matrix ? \n”;
cin >> *ptr_n;
cout << “ enter the elements of A matrix \n”;
for ( int i = 0; i<= *ptr_n -1; ++i) {
for ( int j = 0; j<= *ptr_n -1; ++j)
cin >> ptr_a[i][j];
}
cout << “ enter the elements of B matrix \n”;
for (int i = 0; i<= *ptr_n -1; ++i) {
for (int j = 0; j<= *ptr_n -1; ++j)
cin >> ptr_b[i][j];
}
// matrix addition
for (int i = 0; i<= *ptr_n -1; ++i) {
for (int j = 0; j<= *ptr_n -1; ++j) {
ptr_c[i][j] = ptr_a[i][j] + ptr_b[i][j];
}
}
cout << “ Contents of the C matrix \n”;
for (int i = 0; i<= *ptr_n -1; ++i) {
for (int j = 0; j<= *ptr_n -1; ++j) {
cout << setw(3) << ptr_c[i][j];
}
cout << endl;
}
delete ptr_n;
delete [] ptr_a;
delete [] ptr_b;
delete [] ptr_c;
return 0;
}
Output of the above program
order of the matrix ?
3
enter the elements of A matrix
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
enter the elements of B matrix
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
Contents of the C matrix
3 3 3 3
3 3 3 3
3 3 3 3
3 3 3 3

PROGRAM 7
A program to create memory space for a class object using the new operator and to destroy it using the
delete operator.
//using new and delete operators
#include <iostream.h>

class sample {
private :
int x;
float y;
public :
void getdata();
void display();
};
void sample :: getdata()
{
cout << “ enter an integer value \n”;
cin >> x;
cout << “ enter a ofloating point number \n”;
cin >> y;
}

void sample :: display()


{
cout << “ entered numbers are \n”;
cout << “ x = “ << x << ‘\t’ << “ y = “ << y << endl;
}

int main()
{
sample *ptr;
ptr = new sample;
ptr->getdata();
ptr->display();
delete ptr;
return 0;
}

Output of the above program


enter an integer value
10
enter a floating point
number
2.34
entered numbers are
x = 10 y = 2.34

THIS POINTER

It is well known that a pointer is a variable which holds the memory address of another variable. Using the
pointer technique, one can access the data of another variables indirectly. The this pointer is a variable
which is used to access the address of the class itself. Sometimes, the this pointer may have return data
items to the caller. In other words, the this pointer is a pointer accessible only within the non-static member
functions of a class, struct, or union type. It points to the object for which the member function is called.
Static member functions do not have a this pointer. The general syntax of the this pointer is:
this
this->class_member
(*this).class_member
For example, the following assignment statements are equivalent:
void Date::set Month( int mn ) {
month = mn; // These three statements are equivalent
this->month = mn;
(*this).month = mn;
}

PROGRAM 8

A program to demonstrate how to use the this pointer for accessing the members of a class object.
#include <iostream.h>
class date_info {
public:
int day,month,year;
void setdate(int d,int m, int y);
void display();
};
void date_info :: setdate(int d, int m, int y)
{
//three assignment statements are equivalent
day = d;
this->month = m;
(*this).year = y;
}
void date_info :: display()
{
cout << “Today’s date is : “ << this->day << “/”;
cout << (*this).month << “/” << this->year << ‘\n’;
}
int main()
{
date_info obj;
obj.setdate(10,10,2007);
obj.display();
return 0;
}
Output of the above program
Today’s date is: 10/10/2007
An object’s this pointer is not part of the object itself; it is not reflected in the result of a sizeof
statement on the object. Instead, when a non-static member function is called for an object, the address of
the object is passed by the compiler as a hidden argument to the function.

PROGRAM 9

A program to display the object’s address of a class using this pointer.


//for accessing member data with this pointer
#include <iostream.h>
class sample {
private :
int value;
public :
inline void display();
};
inline void sample ::display()
{
this->value = 20;
cout << “Contents of the value = “ << this->value ;
cout << endl;
}
int main()
{
sample obj1;
obj1.display();
obj2.display();
obj3.display();
return 0;
}
Output of the above program
Object’s address = 0x24e0fff2
Object’s address = 0x24e0fff0
Object’s address = 0x24e0ffee
The above program creates three objects, obj1, obj2, obj3 and displays each object’s address using this
pointer. The display () member function is used to give the address of the object. The this pointer can be
treated like any other pointer to an object. The following is a valid declaration of the class object in C++.
inline void sample ::display()
{
this->value = 20;
cout << “Contents of the value = ” << this->value ;
cout << endl;
}
The above program segment is same as the following:

inline void sample ::display()


{
value = 20;
cout << “Contents of the value = ” << value ;
cout << endl;
}

PROGRAM10

A program to demonstrate how the this pointer is used to access the member data of a class.
//for accessing member data with this pointer
#include <iostream.h>
class sample {
private :
int value;
public :
inline void display();
};
inline void sample ::display()
{
this->value = 20;
cout << “Contents of the value = ” << this->value ;
cout << endl;
}
int main()
{
sample obj1;
obj1.display();
return 0;
}
Output of the above program
Contents of the value = 20
The object’s address is available from within the member function as the this pointer. Most uses of this
are implicit. The expression *this is commonly used to return the current object from a member function:
return *this;
The this pointer is also used to guard against self-reference:
Type of this Pointer
(a) Const Whenever member data is declared as const, it is meant for read only purpose and it cannot be
modified. The const member cannot invoke member functions that are not const.
(b) Volatile The volatile member data is loaded from memory each time it is accessed and it disables certain
optimisations.
It is an error to pass a const object to a member function that is not const. Similarly, it is an error to
pass a volatile object to a member function that is not volatile. Member functions declared as const cannot
change member data—in such functions, the this pointer is a pointer to a const object.
Note that constructors and destructors cannot be declared as const or volatile. They can, however,
be invoked on const or volatile objects.

MUTABLE
The keyword mutable is used to access the const data member of a class. We have already seen that the
this keyword can only be applied to non-static and non-const data members of a class. If a data member
is declared mutable, then it is legal to assign a value to this data member from a const member function.
mutable member-variable-declaration;
For example, the following code will compile without error because m_accessCount has been declared
to be mutable, and therefore can be modified by GetFlag even though GetFlag is a const member function.

PROGRAM 11

A program to demonstrate how to use the mutable modifier for accessing the const member data of a class.
// mutable.cpp
#include <iostream.h>

class abc
{
public:
void setdata(int a);
void display();
void GetFlag() const
{
m_accessCount++;
}
private:
mutable int m_accessCount;
};

void abc :: setdata(int a)


{
m_accessCount = a;
}

void abc::display()
{
cout << “AccessCount = ” << m_accessCount << “\n”;
}

int main()
{
abc obj;
obj.setdata(100);
obj.display();
obj.GetFlag();
return 0;
}
Output of the above program
AccessCount = 100
CONSTRUCTORS

A constructor is a special member function for automatic initialisation of an object. Whenever an object is
created, the special member function, i.e., is the constructor will be executed automatically. A constructor
function is different from all other nonstatic member functions in a class because it is used to initialise
the variables of whatever instance being created. Note that a constructor function can be overloaded to
accommodate many different forms of initialisation.
Syntax rules for writing constructor functions The following rules are used for writing a constructor function:
∑ A constructor name must be the same as that of its class name.
∑ It is declared with no return type (not even void).
∑ It cannot be declared const or volatile but a constructor can be invoked for a const and
volatile objects.
∑ It may not be static.
∑ It may not be virtual.
∑ It should have public or protected access within the class and only in rare circumstances it should be
declared private.
The general syntax of the constructor function in C++ is,
class class_name {
private :
-------
-------
protected :

-------
-------
public :
class_name(); // constructor
-------
-------
};
class_name :: class_name()
{
-------
-------
}
The following examples illustrate the constructor declaration in a class definition.
(1)
class employee {
private :
char name[20];
int ecode;
char address[20];
public :
employee(); // constructor
void getdata();
void display ();
};
employee() :: employee(); // constructor
{
-------
-------
}
(2)
class account {
private :
oat balance;
oat rate;
public :
account() //constructor
{
-------
-------
}
void create_acct();
};

When the constructor function is invoked Constructors and destructors can be explicitly called. A constructor
is automatically invoked when an object begins to live. Under the following circumstances, a constructor
function is invoked automatically by the C++ compiler.
∑ The constructor is called before main () starts for execution
∑ Whenever an object is created in any of the following ways
– a global variable
– a local variable
– or as a static variable.
∑ An auto variable of class is defined within a block and the location of its definition is reached.
∑ A temporary instance of class needs to be created.
∑ During use of the dynamic memory allocation operator new.
The following is an invalid declaration of a constructor function:
(1)
class account {
private :
oat balance;
oat rate;
public :
account() //constructor
{
-------
-------
}
void create_acct();
};
void account :: account() { // error
-------
-------
}
Note that a constructor member function should not be defined with return type or a void type.

PROGRAM 1

A program to demonstrate how to use a special member function, namely, constructor in C++.
#include <iostream.h>
class abc
{
public:
abc() {
cout << “for class constructor\n”;
}
};
int main()
{
abc obj;
return 0;
}
Output of the above program
for class constructor

PROGRAM 2
A program to generate a series of Fibonacci numbers using the constructor where the constructor
member function has been defined in the scope of class definition itself.
//generation of the bonacci series using
// constructor
#include <iostream.h>
class bonacci {
private :
unsigned long int f0,f1, b;
public :
bonacci () // constructor
{
f0 = 0;
f1 = 1;
cout << “Fibonacci series of rst 10 numbers\n”;
cout << f0 << ‘\t’ << f1 <<‘\t’;
b = f0+f1;
}
void increment ()
{
f0 = f1;
f1 = b;
b = f0+f1;
}
void display()
{
cout << b << ‘\t’;
}
}; // end of class construction
int main()
{
bonacci number;
for (int i = 3; i <= 10; ++i) {
number.display();
number.increment();
}
return 0;
}
Output of the above program
Fibonacci series of rst 10 numbers
0 1 1 2 3 5 8 13 21 34

PROGRAM 3

A program to display a series of Fibonacci numbers using the constructor where the constructor member
function has been defined out of the class definition using the scope resolution operator.
//generation of the bonacci series using
// constructor using scope resolution operator
#include <iostream.h>
class bonacci {
private :
unsigned long int f0,f1, b;
public :
bonacci (); // constructor
void increment ();
void display() ;
}; // end of class construction
bonacci :: bonacci() // constructor
{
cout << “Fibonacci series of rst 10 terms\n”;
f0 = 0;
f1 = 1;
b = f0+f1;
cout << f0 << ‘\t’ << f1 << ‘\t’;
}
void bonacci :: increment ()
{
f0 = f1;
f1 = b;
b = f0+f1;
}
void bonacci ::display()
{
cout << b << ‘\t’;
}
int main()
{
bonacci number;
for (int i = 3; i <= 10; ++i) {
number.display();
number.increment();
}
return 0;
}
Output of the above program
Fibonacci series of rst 10 terms
0 1 1 2 3 5 8 13 21 34

PROGRAM 4

A program to simulate a simple banking system in which the initial balance and the rate of interest are
read from the keyboard and these values are initialised using the constructor member function. The
program consists of the following methods:
∑ To initialise the balance amount and the rate of interest using the constructor member function
∑ To make a deposit
∑ To withdraw an amount from the balance
∑ To find the compound interest based on the rate of interest
∑ To know the balance amount
∑ To display the menu options
//demonstration of constructor
//simulation of simple banking system
#include <iostream.h>
class account {
private :
oat balance ;
oat rate;
public :
account(); // constructor
void deposit ();
void withdraw ();
void compound();
void getbalance();
void menu();
}; //end of class de nition
account :: account() // constructor
{
cout << “ enter the initial balance \n”;
cin >> balance;
cout << “ interest rate in decimal\n”;
cin >> rate;
}
//deposit
void account :: deposit ()
{
oat amount;
cout << “ enter the amount : ”;
cin >> amount;
balance = balance+amount;
}
//attempt to withdraw
void account :: withdraw ()
{
oat amount;
cout << “ how much to withdraw ? \n”;
cin >> amount;
if (amount <= balance) {
balance = balance-amount;
cout << “ amount drawn = ” << amount << endl;
cout << “ current balance = ” << balance << endl;
}
else
cout << 0;
}
void account :: compound ()
{
oat interest;
interest = balance*rate;
balance = balance+interest;
cout << “interest amount = ” << interest <<endl;
cout << “ toal amount = ” << balance << endl;
}
void account :: getbalance()
{
cout << “ Current balance = ” ;
cout << balance << endl;
}
void account :: menu()
{
cout << “ d -> deposit\n”;
cout << “ w -> withdraw \n”;
cout << “ c -> compound interest\n”;
cout << “ g -> get balance \n”;
cout << “ q -> quit\n”;
cout << “ m -> menu\n”;
cout << “ option, please ? \n”;
}
int main()
{
class account acct;
char ch;
acct.menu();
while ( (ch = cin.get()) != ‘q’) {
switch (ch) {
case ‘d’ :
acct.deposit();
break;
case ‘w’ :
acct.withdraw();
break;
case ‘c’ :
acct.compound();
break;
case ‘g’ :
acct.getbalance();
break;
case ‘m’:
acct.menu();
break;
} // end of switch statement
}
return 0;
}
Output of the above program
enter the initial balance
1000
interest rate in decimal
0.2
d -> deposit
w -> withdraw
c -> compound interest
g -> get balance
q -> quit
m -> menu
option, please?

g
Current balance = 1000
d
enter the amount : 1000
g
Current balance = 2000
w
how much to withdraw?
500
amount drawn = 500
current balance = 1500
c
interest amount = 300
toal amount = 1800
g
Current balance = 1800
q

11.2.1 Copy Constructors


Copy constructors are always used when the compiler has to create a temporary object of a class object.
The copy constructors are used in the following situations:
∑ The initialisation of an object by another object of the same class.
∑ Return of objects as a function value.
∑ Stating the object as by value parameters of a function.
The copy constructor can accept a single argument of reference to same class type. The purpose of the
copy constructor is copy objects of the class type. The general format of the copy constructor is,
class_name :: class_name (class_name &ptr)
The symbolic representation of the above format is;
X :: X ( X &ptr)
where X is user-defined class name and ptr is pointer to a class object X.
The copy constructor may be used in the following format also using a const keyword.
class_name :: class_name (const class_name &ptr)
The symbolic representation of the above format is,
X :: X ( const X &ptr)
where X is user-defined class name and ptr is pointer to a class object X.
Normally, the copy constructors take an object of their own class as arguments and produce such an
object. The copy constructor usually do not return a function value as constructors cannot return any
function values.
The following program segment demonstrates how to define a copy constructor for finding a series of
Fibonacci numbers.
bonacci :: bonacci() // constructor
{
f0 = 0;
f1 = 1;
b = f0+f1;
}

bonacci :: bonacci( bonacci &ptr) //copy constructor


{
f0 = ptr.f0;
f1 = ptr.f1;
b = ptr. b;
}

PROGRAM 5
A program to generate a series of Fibonacci numbers using a copy constructor where the copy constructor
is defined within the class declaration itself.
//generation of the bonacci series using
// copy constructor
#include <iostream.h>
#include <iomanip>
class bonacci {
public :
unsigned long int f0,f1, b;
bonacci ()
{
f0 = 0;
f1 = 1;
b = f0+f1;
}
bonacci ( bonacci &ptr) {
f0 = ptr.f0;
f1 = ptr.f1;
b = ptr. b;
}
void increment ()
{
f0 = f1;
f1 = b;
b = f0+f1;
}
void display()
{
cout << setw(4) << b;
}
}; // end of class construction
int main()
{
int n;
bonacci obj;
cout << “ How many numbers are to be displayed \n”;
cin >> n;
cout << obj.f0 << setw(4) << obj.f1;
for (int i = 2; i <= n-1; ++i) {
obj.display();
obj.increment();
}
cout << endl;
return 0;
}
Output of the above program
How many numbers are to be displayed
8
0 1 1 2 3 5 8 13

PROGRAM 6

A program to generate a series of Fibonacci numbers using a copy constructor where the copy constructor
is defined out of the class declaration using scope resolution operator.
//generation of the bonacci series using
// copy constructor using scope resolution operator
#include <iostream.h>
#include <iomanip>
struct bonacci {
public :
unsigned long int f0,f1, b;
bonacci (); // constructor
bonacci( bonacci &ptr);// copy constructor
void increment ();
void display() ;
}; // end of class construction
bonacci :: bonacci() // constructor
{
f0 = 0;
f1 = 1;
b = f0+f1;
}
bonacci :: bonacci( bonacci &ptr) //copy constructor
{
f0 = ptr.f0;
f1 = ptr.f1;
b = ptr. b;
}
void bonacci :: increment ()
{
f0 = f1;
f1 = b;
b = f0+f1;
}
void bonacci :: display()
{
cout << setw(4) << b;
}
int main()
{
int n;
bonacci obj;
cout << “How many numbers are to be displayed ?\n”;
cin >> n;
cout << obj.f0 << setw(4) << obj.f1;
for (int i = 2; i <= n-1; ++i) {
obj.display();
obj.increment();
}
cout << endl;
return 0;
}
Output of the above program
How many numbers are to be displayed?
6
0 1 1 2 3 5

11.2.2 Default Constructors


The default constructor is a special member function which is invoked by the C++ compiler without any
argument for initialising the objects of a class. In other words, a default constructor function initialises the
data members with no arguments. It can be explicitly written in a program. In case, a default destructor is
not defined in a program, the C++ compiler automatically generates it in a program. The purpose of the
default constructor is to construct a default object of the class type.
The general syntax of the default constructor function is,
class class_name {
private :
-------
-------
protected :
-------
-------
public :
class_name(); // default constructor
-------
-------
};
class_name :: class_name () {} // without any arguments
The typical form of the default constructor is:
class_name :: class_name (int = 0) {} // without any arguments

Case 1 The default constructor can be declared in the following form:


student() {} // default constructor
// demonstration of default constructor
#include <iostream>
class student {
private :
char name[20];
long int rollno;
char sex;
oat height;
oat weight;
public:
student() {} // default constructor
void display();
}; // end of class declaration

Case 2 The default constructor can be declared in the following form also:
student(int = 0) {} // constructor

// demonstration of default constructor


#include <iostream>
class student {
private :
char name[20];
long int rollno;
char sex;
oat height;
oat weight;
public:
student(int = 0) {} // constructor
void display();
}; // end of class declaration

Case 3 If the default constructor is not declared explicitly, then it will be created automatically by the
compiler.
#include <iostream>
class student {
private :
char name[20];
long int rollno;
char sex;
oat height;
oat weight;
public:
void display();
}; // end of class declaration

PROGRAM 7

A program to demonstrate the default initialisation of the constructor member function of a class object
of the students’ information system such as name, roll number, sex, height and weight.
// demonstration of default constructor
#include <iostream.h>
class student {
private :
char name[20];
long int rollno;
char sex;
float height;
float weight;
public :
student(); // constructor
void display();
};
student :: student()
{
name[0] = ‘\0’;
rollno = 0;
sex = ‘\0’;
height = 0;
weight = 0;
}
void student :: display()
{
cout << “ name = ” << name <<endl ;
cout << “ rollno = ” << rollno <<endl;
cout << “ sex = ” << sex << endl;
cout << “ height = ” << height << endl;
cout << “ weight = ” << weight << endl;
}
int main()
{
student a;
cout << “ demonstration of default constructor \n”;
a.display();
return 0;
}
Output of the above program
demonstration of default constructor
name =
roll no = 0
sex =
height = 0
weight = 0

PROGRAM 8

A program to demonstrate the default initialisation of the constructor member function of a class object
where the default constructor is defined within the scope of the class definition itself.
// demonstration of default constructor
#include <iostream.h>
#include <string>
class student {
private :
char name[20];
long int rollno;
char sex;
oat height;
oat weight;
public :
student(char na[] =“\0”,long int rn = 0,char sx = ‘\0’,
oat ht = 0, oat wt=0);// constructor
void display();
};
s tudent:: s tudent(char na[] ,long int rn,ch ar sx , oat ht, float wt)
{
strcpy(name, na);
rollno = rn;
sex = sx;
height = ht;
weight = wt;
}
void student :: display()
{
cout << “ name = ” << name <<endl ;
cout << “ rollno = ” << rollno <<endl;
cout << “ sex = ” << sex << endl;
cout << “ height = ” << height << endl;
cout << “ weight = ” << weight << endl;
}
int main()
{
student a;
cout << “ demonstration of default constructor \n”;
a.display();
return 0;
}
Output of the above program
demonstration of default constructor
name =
rollno = 0
sex =
height = 0
weight = 0

PROGRAM 9
A program to demonstrate the default initialisation of the constructor member function of a class object
where the default constructor is created by the compiler automatically when the default constructor is
not defined by the user.
#include <iostream.h>
class student {
private :
char name[20];
long int rollno;
char sex;
float height;
float weight;
public :
void display();
};
void student :: display()
{
cout << “ name = ” << name <<endl ;
cout << “ rollno = ” << rollno <<endl;
cout << “ sex = ” << sex << endl;
cout << “ height = ” << height << endl;
cout << “ weight = ” << weight << endl;
}
int main()
{
student a;
a.display();
return 0;
}
Output of the above program
name = �������
rollno = 1108544020
sex = X
height = 3.98791e-34
weight = 36.7598
Automatic variables are initialised with a garbage value if it is not initialised by the user explicitly.
11.2.3 Overloading Constructors
The overloading constructor is a concept in OOPs in which the same constructor name is called with
different arguments. Depending upon the type of argument, the constructor will be invoked automatically
by the compiler to intialise the objects.

PROGRAM 10

A program to demonstrate how to define, declare and use the overloading of constructors to initialise the
objects for different data types.

//overloading of constructor
#include <iostream.h>
class abc {
public:
abc();
abc(int);
abc(float);
abc(int, float);
};
abc :: abc()
{
cout <<“calling default constructor \n”;
}
abc :: abc (int a)
{
cout << “\n calling constructor with int \n”;
cout << “ a = ” << a << endl;
}
abc :: abc (float fa)
{
cout <<“\n calling constructor with oating point number \n”;
cout <<“ fa = ” << fa << endl;
}
abc :: abc(int a, float fa)
{
cout << “ \n calling constructor with int and oat \n”;
cout << “ a = ” << a << endl;
cout << “ fa = ” << fa << endl;
}
int main()
{
abc obj;abc(10);abc(1.1);
abc(20,-2.2);
return 0;
}

Output of the above program


calling default constructor

calling constructor with int


a = 10

calling constructor with oating point number


fa = 1.1

calling constructor with int and oat


a = 20
fa = -2.2

11.2.4 Constructors in Nested Classes


It is well known that a constructor is a special member function which is used to initialise the class objects
whenever an object is created. The constructor member function can be used to initialise the class objects
of nested classes. The nested class is a technique in which a class is declared as a member of another class.
In other words, a class within a class is called as nested class. The scope rules to access the nested class
constructor is the same as that of the member functions of the nested classes. The scope resolution operator
(::) is used to identify the outer and inner class objects and the constructor member functions.

PROGRAM 11
A program to demonstrate how to declare, define and call a constructor member function in a nested class.

#include <iostream.h>
class abc {
public:
abc();
class x {
public:
x();
};
};
abc:: abc()
{
cout << “abc - class constructor \n”;
}
abc::x :: x()
{
cout << “x - class constructor \n”;
}
int main()
{
abc obj;
abc::x obj2;
return 0;
}
Output of the above program
abc - class constructor
x - class constructor

PROGRAM 12
A program to demonstrate how to declare, define and call a constructor member function in a nested
class. The firing order of the nested class constructor is illustrated in the following program.

#include <iostream.h>
class abc {
public:
abc();
class x {
public:
x();
class y {
public:
y();
class z {
public:
z();
};
};
};
};
abc:: abc()
{
cout << “abc - class constructor \n”;
}
abc::x :: x()
{
cout << “x - class constructor \n”;
}
abc::x :: y :: y()
{
cout << “y - class constructor \n”;
}
abc::x ::y :: z :: z()
{
cout << “z - class constructor \n”;
}
int main()
{
abc obj1;
abc::x obj2;
abc::x::y obj3;
abc::x::y::z obj4;
return 0;
}

Output of the above program


abc - class constructor
x - class constructor
y - class constructor
z - class constructor

DESTRUCTORS

A destructor is a function that automatically executes when an object is destroyed. A destructor function gets
executed whenever an instance of the class to which it belongs goes out of existence. The primary usage of the
destructor function is to release space on the heap. A destructor function may be invoked explicitly.
Syntax Rules for Writing a Destructor Function The rules for writing a destructor function are:
∑ A destructor function name is the same as that of the class it belongs except that the first character of
the name must be a tilde (~).
∑ It is declared with no return types (not even void) since it cannot ever return a value.
∑ It cannot be declared static, const or volatile.
∑ It takes no arguments and therefore cannot be overloaded.
∑ It should have public access in the class declaration.
The general syntax of the destructor function in C++ is,
class class_name {
private :
// data variables
// methods
protected :
// data
public :
class_name(); // constructor
~class_name(); // destructor
// other methods
};
The following examples illustrate the destructor function declaration in a class definition:
(1)
class employee {
private :
char name[20];
int ecode;
char address[20];
public :
employee(); // constructor
~employee(); // destructor
void getdata();
void display ();
};
(2)
class account {
private :
float balance;
float rate;
public :
account(); //constructor
~account(); // destructor
void create_acct();
};

When the Destructor Function is Invoked Under the following circumstances, a destructor function is invoked:
∑ After the end of main () for all static, local to main () and global instances of class.
∑ At the end of each block containing the auto variable of class.
∑ At end of each function containing an argument of class.
∑ To destroy any unnamed temporaries of class after their use.
∑ When an instance of class allocated on the heap is destroyed via delete.

PROGRAM 13
A program to simulate a simple banking system in which the initial balance and the rate of interest are
read from the keyboard and these values are initialised using the constructor member function. The
destructor member function is defined in this program to destroy the class objects created using the
constructor member function. The program consists of the following methods:
∑ To initialise the balance and the rate of interest using the constructor member function.
∑ To make a deposit.
∑ To withdraw an amount from the balance.
∑ To find the compound interest based on the rate of interest.
∑ To know the balance amount.
∑ To display the menu options.
∑ To destroy the object of class, the destructor member function is defined.
//program for class demonstration
// constructor and destructor
#include <iostream.h>
class account {
private :
float balance;
float rate;
public :
account(); // constructor
~account(); // destructor
void deposit ();
void withdraw ();
void compound();
void getbalance();
void menu();
}; //end of class de nition
account :: account() // constructor
{
cout << “ enter the initial balance \n”;
cin >> balance;
cout << “ interest rate \n”;
cin >> rate;
}
account :: ~account() // constructor
{
cout << “ data base has been deleted \n”;
}
//deposit
void account :: deposit ()
{
float amount;
cout << “ enter the amount ”;
cin >> amount;
balance = balance+amount;
}
//attempt to withdraw
void account :: withdraw ()
{
float amount;
cout << “ how much to withdraw ? \n”;
cin >> amount;
if (amount <= balance) {
balance = balance-amount;
cout << “ amount drawn = ” <<amount << endl;
cout << “ current balance = ” << balance << endl;
}
else
cout << 0;
}
void account :: compound ()
{
float interest;
interest = balance*rate;
balance = balance+interest;
cout << “interest amount = ” << interest <<endl;
cout << “ toal amount = ” << balance << endl;
}

void account :: getbalance()


{
cout << “ Current balance = ” ;
cout << balance << endl;
}
void account :: menu()
{
cout << “ d -> deposit\n”;
cout << “ w -> withdraw\n”;
cout << “ c -> compound interest\n”;
cout << “ g -> get balance\n”;
cout << “ m -> menu \n”;
cout << “ q -> quit \n”;
cout << “ option, please ? \n”;
}
int main()
{
account acct;
char ch;
acct.menu();
while ( (ch = cin.get()) != ‘q’) {
switch (ch) {
case ‘d’ :
acct.deposit();
break;
case ‘w’ :
acct.withdraw();
break;
case ‘c’ :
acct.compound();
break;
case ‘g’ :
acct.getbalance();
break;
case ‘m’:
acct.menu();
break;
} // end of switch statement
}
cout << endl;
return 0;
}
Output of the above program
enter the initial balance
1000
interest rate
0.2
d -> deposit
w -> withdraw
c -> compound interest
g -> get balance
m -> menu
q -> quit
option, please?
d
enter the amount
500
g
Current balance = 1500

w
how much to withdraw?
1000
amount drawn = 1000
Current balance = 500
c
interest amount = 100
toal amount = 600
q
data base has been deleted

11.3.1 Destructors in Nested Classes


It is well known that a destructor is a special member function which is used to destroy the class objects
automatically whenever an object is released. The destructor member function can also be used to implement
the nested class objects. The firing order of destructor under nested class is that the innermost class object
will be released first and so on. The scope rules to access the nested class destructor is the same as that of the
member functions of the nested classes. The scope resolution operator (::) is used to identify the outer and
inner class objects and the constructor/destructor member functions.

PROGRAM 14

A program to demonstrate how to declare, define and call a destructor member function in a nested class.
#include <iostream.h>

class abc {
public:
~abc();
class x {
public:
~x();
class y{
public:
~y();
class z {
public:
~z();
};
};
};
};
abc:: ~abc()
{
cout << “abc - class destructor \n”;
}
abc::x :: ~x()
{
cout << “x - class destructor \n”;
}
abc::x ::y :: ~y()
{
cout << “y - class destructor \n”;
}
abc::x ::y :: z :: ~z()
{
cout << “z - class destructor \n”;
}
int main()
{
abc obj1;
abc::x obj2;
abc::x::y obj3;
abc::x::y::z obj4;
return 0;
}
Output of the above program

z - class destructor
y - class destructor
x - class destructor
abc - class destructor

PROGRAM 15

A program to demonstrate how to declare, define and call a constructor and a destructor member
function in a nested class. This program illustrates the firing order of constructor and destructor under
the nested class.
#include <iostream.h>
class abc {
public:
abc();
~abc();
class x {
public:
x();
~x();
class y{
public:
y();
~y();
class z {
public:
z();
~z();
};
};
};
};
abc:: abc()
{
cout << “abc - class constructor \n”;
}
abc:: ~abc()
{
cout << “abc - class destructor \n”;
}
abc::x :: x()
{
cout << “x - class constructor \n”;
}
abc::x :: ~x()
{
cout << “x - class destructor \n”;
}
abc::x ::y :: y()
{
cout << “y - class constructor \n”;
}
abc::x ::y :: ~y()
{
cout << “y - class destructor \n”;
}
abc::x ::y :: z :: z()
{
cout << “z - class constructor \n”;
}
abc::x ::y :: z :: ~z()
{
cout << “z - class destructor \n”;
}
int main()
{
abc obj1;
abc::x obj2;
abc::x::y obj3;
abc::x::y::z obj4;
return 0;
}
Output of the above program
abc - class constructor
x - class constructor
y - class constructor
z - class constructor
z - class destructor
y - class destructor
x - class destructor
abc - class destructor

You might also like