Vous êtes sur la page 1sur 34

OOP Features

Classes and objects and Methods and properties


A class is a user defined data type like a structure or a union. A class consists of data variables and functions. These
variables and functions are called members of the class. The variables are called data members and functions are
called member functions. The member functions are also called methods. The data members are called properties of
the class. An object is the instance of the class. An object is like a compound variable of the user defined type. It
links both code and data. Within the object, members of the class can be public or private to the object. The
declaration of a class is syntactically same as structure. The class is declared using keyword class. The general form
of the declaration of the class is:-
class class_name
{
access_specifier:
data functions
access_specifier:
data functions

} object_list;

The object_list is optional. The object_list is used to declare objects of the class. The class_name is the name of the
class. The access_specifier can either public, private or protected. The members of the class by default are private to
the class. If the access_specifier is private then members of the class are not accessible outside the class. If the
access_specifier is public then members of the class can be accessed from outside the class. The protected
access_specifier is needed at the time of inheritance. The members can be accessed using an object’s name, a dot
operator and name of the member. Here is a program which shows how classes and objects are created.

#include<iostream>
using namespace std;

class cube
{
public:
double side;
double volume()
{
return(side*side*side);
}
};

int main()
{
double volume1=0;
cube c1,c2;
cout << "Enter the lenght of the cube" << endl;
cin >> c1.side;
cout << "The volume of the cube is : " << c1.volume() << endl;
c2.side=c1.side +2;
cout << "The volume of the second cube is : " << c2.volume() << endl;
return(0);
}

The result of the program is:-


The program consists of a class cube which has data member side of type double and member function which
calculates the volume of the cube. The statement

class cube

declares a class cube. The statements

public:
double side;
double volume()
{
return(side*side*side);
}

declare that access_specifier is public for data member side and member function volume. These members can be
accessed from the other parts of the program. The statement

cube c1,c2;

declares two objects c1 and c2 of type cube. The statement

cin >> c1.side;

access the data member of the cube. The member is accessed by specifying the name of the object as c1 then dot
operator and then name of the variable side. The length entered by the user is stored in c1.side. In the statement

cout << "The volume of the cube is : " << c1.volume() << endl;

c1.volume() calls the member function volume which returns the volume of the cube of side whose length is entered
by the user. The statement

c2.side=c1.side +2;

equates the side of object c2 to side of object c1 increased by 2. The objects c2 and c1 are different. The statement

cout << "The volume of the second cube is : " << c2.volume() << endl;

displays the volume of second object c2.

Constructor and Destructor

Constructors are used in order to initialize the objects. A constructor is a special kind of a function which is the
member of the class. The name of the constructor is same as name of the class. A constructor is automatically called
when object is created. A constructor does not have a return type.
A default constructor is a constructor with no parameters. If no constructor is defined by the user then compiler
supplies the default constructor. Once the constructor is defined by the user then compiler does not supply default
constructor and then user is responsible for defining default constructor.

A destructor is the complement of the constructor. It is used to destroy the objects. The objects are destroyed in
order to deallocate the memory occupied by them. The name of the destructor is same as the name of the constructor
as is preceded by a tilt operator ‘~’. A destructor for objects is executed in the reverse order of the constructor
functions.

Here is a program which shows how constructors and destructors are used.

#include<iostream>
using namespace std;

class cube
{
public:
double side;
double volume()
{
return(side*side*side);
}
cube(double side1)
{
cout << "A constructor is called" << endl;
side=side1;
}
cube()
{
cout << "A default constructor is called " << endl;
}
~cube()
{
cout << "Destructing " << side << endl;
}
};

int main()
{
cube c1(2.34);
cube c2;
cout << "The side of the cube is: " << c1.side << endl;
cout << "The volume of the first cube is : " << c1.volume() << endl;
cout << "Enter the length of the second cube : " ;
cin >> c2.side;
cout << "The volume of second cube is : " << c2.volume() << endl;
return(0);
}

The result of the program is:-


The statement

cube(double side1)
{
cout << "A constructor is called" << endl;
side=side1;
}
declares the constructor of the class cube. The name of the constructor is same as the name of the class. There is no
return type in the constructor. It will initialize the value of data member side. The statement

cube()
{
cout << "A default constructor is called " << endl;
}

declares a default constructor. The statement

~cube()
{
cout << "Destructing " << side << endl;
}

declares a destructor to deallocate the objects. The statement

cube c1(2.34);

creates an object c1 of type cube. A constructor is automatically called and initializes the data member side with
value 2.34. The statement

cube c2;

creates an object of type c2. When object c2 is created a default constructor is called and the message will be
printed. The statements

cout << "The side of the cube is: " << c1.side << endl;
cout << "The volume of the first cube is : " << c1.volume() << endl;

displays the side and volume of the cube where side has value 2.34. The statement

cin >> c2.side;

will set the value of the side of the object c2 as entered by the user. At the end of the program objects are deallocated
in the reverse order in which constructors are called. First object c2 is deallocated whose side is 2.5 and then object
c1 is deallocated whose side is 2.34.
Advantage of the classes:-

It provides protection to the data. The members of the class are by default private to the class while the members of
the structure are public. OOP features allow programmer to easily handle complex problems and multi file projects.
They help in modeling real world objects such as bank accounts and their related transactions.

Go to the previous lesson or proceed to the next lesson


Table of contents
Encapsulation, private public. Sections

The packaging of data values and member functions within one object is called an encapsulation. For example an
object of class cube contains data member as side of the cube and member function volume of the cube. It is also
called data hiding which helps to maintain the integrity of the object. It saves the data from misuse and outside
interference. The data cannot be accessed directly but access controls can be specified in order to obtain the
information. The data or object can be made public or private depending on the needs. The data which is private is
not accessible outside the scope of the object. When the data is public it can be accessed by the other parts of the
program.

Here is a program which shows how private and public members are accessed. The program consists of a class
rectangle which has two data members such as length and breadth and the member functions area() and len(). The
private data member length cannot be accessed directly. It is accessed using a function len() which is public and
which returns the private data member length.

#include<iostream>
using namespace std;

class rectangle
{
private:
double length;

public:
double breadth;
double area()
{
return(length*breadth);
}
double len()
{
return(length);
}
rectangle(double lenght1,double breadth1)
{
length=lenght1;
breadth=breadth1;
}
};

int main()
{
rectangle r1(3.5,4.6);
double a=r1.len();
double b=r1.breadth;
cout << "The lenght is : " << a << endl;
cout << "The breadth is : " << b << endl;
cout << "The area is : " << r1.area() << endl;
return(0);
}

The result of the program is:-

The statement

private:
double length;

declares that data member length of type double which has access specifier as private. It cannot be accessed directly.
The statements

public:
double breadth;
double area()
{
return(length*breadth);
}
double len()
{
return(length);
}

declares that data member breadth and member functions len() and area() are public. The member function len() is
used to return the data member length which cannot be accessed directly. The statement

rectangle r1(3.5,4.6);

declares an object r1 of rectangle. The constructor initializes the length and breadth of the object as soon as it is
created. The statement

double a=r1.len();

returns the length of the object. The data member length cannot be accessed directly as it is declared private
therefore member function len() is used to return the value of length. The statement double a=r1.length in main()
function is invalid as data member length is inaccessible. The statement

double b=r1.breadth;

equates the value of b to the value of breadth of object r1. The statement

cout << "The area is : " << r1.area() << endl;

displays the area of the rectangle.

Go to the previous lesson or proceed to the next lesson


Table of contents
Inheritance, Samples of using inheritance

Inheritance is the property by which one object can inherit the properties of the other object. A general class can be
inherited by the other classes. A class that is inherited is called a base class. A class which is inheriting another
class is called a derived class. When a class inherits another class, members of the base class become the members
of the derived class. The general form of inheritance is:-

class derived_name : access_specifier base_name


{
};

The derived_name is the name of the derived class. The base_name is the name of the base class. The
access_specifier can be private, public or protected. If the access_specifier is public then all public members of the
base class become public members of the derived class and protected members of the base class become the
protected members of the derived class. If the access_specifier is private then all public and protected members of
the base class will become private members of the derived class. If the access_specifier is protected then the public
and protected members of the base class become the protected members of the derived class. Whether
access_specifier is public, private or protected, private members of the base class will not be accessed by the
members of the derived class.

The access_specifier protected provides more flexibility in terms of inheritance. The private members of the base
class cannot be accessed by the members of the derived class. The protected members of the base class remain
private to their class but can be accessed and inherited by the derived class. The protected members of the base class
will remain private to the other elements of the program.

A derived class can inherit one or more base classes. A constructor of the base is executed first and then the
constructor of derived class is executed. A destructor of derived class is called before the destructor of base class.
The arguments to the base class constructor can be passed as follows:-

derived_constructor (argument list): base1 (arg_list)


base2(arg_list1)

baseN(arg_list)

The derived_constructor is the name of the derived class. The argument list is list of the data members of the derived
class. The base1 is name of the base class. The arg_list is the list of the members of the base class. Here is a program
which illustrates the features of inheritance.

#include<iostream>
using namespace std;

class shape
{

private :
double length;

protected:
double breadth;

public :

double len()
{
return(length);
}
shape(double length1,double breadth1)
{
length=length1;
breadth=breadth1;
}
//shape() { }
};

class shape1
{
public:
double height;

shape1(double height1)
{
height=height1;
}
//shape1() { }
};

class cuboid : public shape, private shape1


{
public:

cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1)


{
cout << " A constructor is called " << endl;
}

double volume()
{
return(height*breadth*len());
}
double bre()
{
return(breadth);
}
double ht()
{
return(height);
}
};

int main()
{
cuboid c1(2.4,3.5,6.7);
cout << "The length of the cuboid is : " << c1.len() << endl;
cout << "The breadth of the cuboid is : " << c1.bre() << endl;
cout << "The height of the cuboid is : " << c1.ht() << endl;
cout << "The volume of the cuboid is : " << c1.volume() << endl;
return(0);
}
The result of the program is:-

The program has two base classes shape and shape1 and one derived class called cuboid which inherits shape as
public and shape1 as private. The public and protected members of shape become pubic and protected members of
derived class cuboid. The private members of shape remain private to the class shape. The members of shape1 class
become the private members of the derived class cuboid.

The statement

class cuboid : public shape, private shape1

states that class cuboid inherits class shape as public and class shape1 as private. The statement

cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1)


{
cout << " A constructor is called " << endl;
}

declares the constructor of the class cuboid. When constructor of class cuboid is called first constructor of shape is
executed and then constructor of shape1 is executed and after that the constructor of cuboid is executed. The
statements

double volume()
{
return(height*breadth*len());
}

calculate the volume of the cuboid. The class cuboid cannot access the private data member length of the shape
class. It access the length by calling the function len() which returns the private data member length. The data
member breadth becomes the protected member of the class cuboid. The height which is public member of shape1
class becomes the private member of the class cuboid as it inherits the shape 1 class as private. The statements

double bre()
{
return(breadth);
}

returns the breadth of the cuboid as data member breadth cannot be accessed outside the class as it is protected
member of cuboid. The statement

double ht()
{
return(height);
}

returns the height of the cuboid as data member height cannot be accessed outside the class as height is the private
data member of the class cuboid. The statement
cuboid c1(2.4,3.5,6.7);

creates an object c1 of type cuboid. The constructor is called to initialize the values of the cuboid. The constructor of
shape is executed and then constructor of shape1 is executed and then finally constructor of cuboid is executed. The
statement

cout << "The length of the cuboid is : " << c1.len() << endl;

displays the length of the cuboid as c1.len() calls the len() function of class shape which is also the public member
function of cuboid. The statement

cout << "The breadth of the cuboid is : " << c1.bre() << endl;

displays the breadth of the cuboid. As the data member breadth cannot be accessed directly as it is protected member
of the class cuboid so the function bre() returns the breadth of the cuboid. The statement

cout << "The height of the cuboid is : " << c1.ht() << endl;

displays the height of the cuboid. The data member height cannot be accessed directly as it is private member of
class cuboid so it is accessed through the function ht() which returns height.

Go to the previous lesson or proceed to the next lesson


Table of contents
Loops

Before reading this tutorial, you should have knowledge of switch statements.

Loops are iteration statements. Loop provides a mechanism to execute same sequence of instructions repeatedly
until a condition is reached. There are two elements of the loop: the body of loop which is to be executed number of
times and a loop condition which terminates the loop when a particular condition is met. The three different kinds
of a loop are: -

• The for loop


• The while loop
• The do while loop

The for loop

The for loop is used to execute same sequence of statements for the predetermined number of times. The general
form of the for loop is: -

for(initialization; condition; iteration_expression)


{
statement;
}

The initialization is used to initialize the control variable of the loop. The initialization is executed once at the
beginning of the loop. The condition is checked at the beginning of every iteration and if the condition is false then
the loop is terminated. The iteration_expression is executed at the end of each loop iteration. It modifies the control
variables of the loop initialized in the beginning. Here is a program which illustrates the working of the for loop.
The result of the program is: -

The Infinite loop

The for loop can be used to create infinite loop. The infinite loop can be made by leaving the conditional expression
empty. Here is the program of the infinite loop .
The statement
cout << “infinite loop” << endl;

is executed infinite times as there is no condition expression in the for statement. The infinite loop can be broken
using an if and break statement. Here is the program which shows how to discontinue the infinite loop.

The result of the program is:-

Switch Statement

Before reading this tutorial, you should have knowledge of if else statements.
The switch statement is a type of control structure. The general form of a switch statement is

switch (expression)

case constant 1 :
statement sequence
break;

case constant 2 :
statement sequence
break;
.
.
default:
statement sequence

The switch statement allows doing multiple selections depending upon the value of expression. It tests the value of
the expression against the integer or character constants. The value of the expression must be integer or character.
The value of the expression is tested against the constants in the case statements. When a correct match is found
sequence of statements associated with the constant is executed until the break statement or the end of the switch
statement is reached. If no match is found then sequence of statements associated with default is executed. The case
values appear in case labels. No two or more case labels can contain same constant values. The case values can
occur in any sequence. Here is a program which illustrates the working of switch statement.

The result of the program is: -


The break statement is necessary as it switches the control to the statement following the switch statement after
executing sequence of statements associated with case value. If the break statement is omitted then the sequence of
statements for all the following cases are executed till a break statement is encountered or end of the switch is
reached. Here is a program which shows how the statements are executed when there is no break statement.

The result of the program is: -


The user has entered value 1. The value of the variable c is 1. The switch statement is executed. The value of the
variable c is matched against the constants in the case labels. It matches with the value of the first case statement. As
there is no break statement the execution is transferred to the statement

case (2) :

As there is no break statement associated with this case statement also the control is transferred to the third case
statement

case (3) :

The next statement

cout << “ You have chosen one of the first 3 items” << endl;

is executed. Then the statement

break;

is executed and control is transferred to the statement following the switch statement. Omitting the break statement
can be helpful when sequence of statements for two or more case statements is same. For example, in this program
statement

cout << You have chosen one of the first 3 items “ <<

is same for first 3 case statements. Instead of typing the same statement along with every case label you can ignore
the break statement with the case statements and insert the break statement where termination is necessary. It avoids
unnecessary duplication of sequence of statements.

The statement switch can be used instead of if statement. Instead of using ifs statements for checking the expression
against two or more constant values, switch should be used. Here is a program which performs the same function but
uses ifs statements.
The task of writing nested ifs is tedious and switch should be used.

Arrays
An array is a collection of several data items of the same data type. It consists of several contiguous memory
locations storing data. It removes the cumbersome task of defining separate variables for each data item. A single
variable can be used to store one or more data items. For example, if you want to store ages of 10 students of a class,
you can easily declare an array of integer type of size 10 instead of declaring 10 variables of integer type each
storing age of a student. The general form of the single dimension array is:-

type variable_name[size];

The type is the base type of the array and which is the type of each of the element of the array. The size is the no of
the elements in the array. The variable_name is the name of the identifier holding the array. For example,

int age [10];

The age is an array of type integer whose size is 10. It can hold 10 data values. The specific element in the array can
be accessed using an index. An index is the offset from the first element of the array. For example, first element has
an index of 0 while the third element has an index of 2. The integer age has elements from age[0] to age[9]. Here is
a program which illustrates the working of arrays.
#include<iostream>
using namespacestd

#include<iostream>
using namespace std;
int main ()
{
int age[10];
int i,sum=0, avg=0;
int max=0,min=100;
for(i=0;i<10;i++)
{
cout << "Enter the age of the student " << i+1 <<endl;
cin >> age[i];
}
for(i=0;i<10;i++)
{
sum=sum+age[i];
if(age[i]>max)
{
max=age[i];
}
if(age[i]<min)
{
min=age[i];
}
}
avg=sum/10;
cout << "Average age of the students of the class : " << avg << endl;
cout << "Maximum age of the student of the class : " << max << endl;
cout << "Minimum age of the student of the class : " << min << endl;
return(0);
}

The result of the program is:-

In the program the array is declared by the statement

int age[10];

age is the identifier of the array which is of type integer and whose size is 10. In the for loop user is asked to enter
the age of the student, the age is stored in the element of the array by the statement

cin >> age[i];

here i is the index of the array. The index starts from 0. In the next for loop, average age, minimum age and
maximum age of the students is calculated. Each element is accessed by index i. The sum of the elements of the
array is calculated by the statement
sum=sum+age[i];
age[i] is the (i+1)th element of the array. The maximum age is calculated by the if statement
if(max>age[i])
{
max=age[i];
}
The minimum age is calculated by the another if statement

if(min<age[i])
{
min=age[i];
}
The average is calculated by the statement

avg=sum/10;

The total no bytes used to store an array is equal to


Total bytes=size of(base type)×size of array.

Initializing Arrays

The arrays can be initialized by giving the initial values in a list and enclosed in curly brackets, which is placed after
the equal sign which is put after the declaration of the array. For example,

int age[5]={12,13,10,24,15};

elements of the array have values 12, 13, 10, 24, 15. The elements age[0] has value 12 and age[4] will have 15. If
the elements of the array are not initialized then they take some garbage value before they are assigned to some
specified value. There is also another way of initializing all the elements of the array to be zero. For example,

int age[5]={0};

will initialize all the elements of the array age to be zero. If you want some of the elements to be initialized with
specific value and rest of the values to be zero then here is an example.

int age[5]={12,13};

The elements age[0] and age[1] will be initialized to 12 and 13 respectively and rest of the elements will be
initialized to zero.

Null Terminated Strings

The most common use of one dimensional array is for character strings. The null terminated string is a character
array with a null character at the end. The characters form the string with a null character indicating the termination
of the string. A null terminated string can be declared as

char name[10];

it will hold 10 characters with a null at the end. The size of the array can be more than the length of the array. The
array can be initialized as

char name[10]={'j','e','s','u','s'};

The first 5 elements are initialized and rest elements are null characters. Here is a program which calculates the
length of the string.
#include<iostream>
using namespace std;

int main()
{
char name[15];
int i=0;
cout << " Enter your name " << endl;
cin >> name;
while(name[i]!='\0')
{
i++;
}
cout << "Lenght of the name is : " << i << endl;
return(0);
}

The result of the program is

The character array is declared by the statement

char name[15];

The length of the name can be at most 15. The arrays is assigned by taking the input from the user by the statements

cout << " Enter your name " << endl;


cin >> name

Variable name is assigned the string entered by the user. Each element of the array is referenced and checked
whether it is null or not by the statement

while(name[i]!='\0')

Until a null character is not encountered variable i is incremented by the statement

i++;

When a null character is encountered while loop is terminated and length is printed by the statement

cout << "Length of the name is : " << i << endl;

Multidimensional Arrays

The multidimensional arrays are arrays of arrays. The general form of a multidimensional array is: -
type variable_name[Size1][Size2]..[Size n];
The two dimensional array can be declared as

int age[2][5];

this array has two rows and 5 columns. The three dimensional array can be declared as

int age[2][3][5];

When an element of the array of n dimensional is referenced it uses n index values. For example first element of a
two dimensional array declared above is referred as age[0][0] as the index starts from zero and last element is
referred as age[1][4]. Here is a program which calculates the average of the elements of the row of the two
dimensional array.

#include<iostream>
using namespace std;

int main ()
{
int age[2][5]= { {12,13,14,15,15}, { 12,16,17,13,12}};
int i,j;
int sum=0,avg=0;
for(i=0;i<2;i++)
{
for(j=0;j<5;j++)
{
sum=sum+age[i][j];
}
avg=sum/5;
cout << "Average of the elements of the row " << i+1 << " is " << avg << endl;
sum=0;
}
return(0);
}

The result of the program is: -

The program initializes and declares the two dimensional array by the statement

int age[2][5]= { {12,13,14,15,15}, { 12,16,17,13,12}};

Elements of the first row and second row are initialized as {12,13,14,15,15} and
{ 12,16,17,13,12} respectively. The elements are accessed using the statement as

sum=sum+age[i][j];

age[i][j] refers to the element of row i and column j. This statement calculates the sum of the elements of the row.
After the sum of the elements of a row is calculated then average is calculated by the statement.

avg=sum/5;
sum is again initialized to zero. Then again the same process repeats for the second row.
Pointers
Before reading this tutorial, you should have knowledge of arrays.
A pointer is a variable that is used to store a memory address. The address is the location of the variable in the
memory. Pointers help in allocating memory dynamically. Pointers improve execution time and saves space.
Pointer points to a particular data type. The general form of declaring pointer is:-

type *variable_name;

type is the base type of the pointer and variable_name is the name of the variable of the pointer. For example,

int *x;
x is the variable name and it is the pointer of type integer.

Pointer Operators

There are two important pointer operators such as ‘*’ and ‘&’. The ‘&’ is a unary operator. The unary operator
returns the address of the memory where a variable is located. For example,

int x*;
int c;
x=&c;

variable x is the pointer of the type integer and it points to location of the variable c. When the statement

x=&c;

is executed, ‘&’ operator returns the memory address of the variable c and as a result x will point to the memory
location of variable c.

The ‘*’ operator is called the indirection operator. It returns the contents of the memory location pointed to. The
indirection operator is also called deference operator. For example,

int x*;
int c=100;
int p;
x=&c;
p=*x;

variable x is the pointer of integer type. It points to the address of the location of the variable c. The pointer x will
contain the contents of the memory location of variable c. It will contain value 100. When statement

p=*x;

is executed, ‘*’ operator returns the content of the pointer x and variable p will contain value 100 as the pointer x
contain value 100 at its memory location. Here is a program which illustrates the working of pointers.

#include<iostream>
using namespace std;

int main ()
{
int *x;
int c=200;
int p;
x=&c;
p=*x;
cout << " The address of the memory location of x : " << x << endl;
cout << " The contents of the pointer x : " << *x << endl;
cout << " The contents of the variable p : " << p << endl;
return(0);
}

The result of the program is:-

In the program variable x is the pointer of integer type. The statement

x=&c;

points variable x to the memory location of variable c. The statement

p=*x;

makes the contents of the variable p same as the contents of the variable c as x is pointing to the memory location of
c. The statement

cout << " The address of the memory location of x : " << x << endl;

prints the memory address of variable x which it is pointing to. It prints the hexadecimal address 0012FF78. This
address will be different when the program is run on different computers. The statement

cout << " The contents of the pointer x : " << *x << endl;

prints the contents of memory location of the variable x which it is pointing to. The contents are same as the variable
c which has value 200. The statement

cout << " The contents of the variable p : " << p << endl;

has the same output 200 as the statement above. The contents of variable p is same as the contents of the pointer x.

Pointer Arithmetic

There are only two arithmetic operations that can be performed on pointers such as addition and subtraction. The
integer value can be added or subtracted from the pointer. The result of addition and subtraction is an address. The
difference of the two memory addresses results an integer and not the memory address. When a pointer is
incremented it points to the memory location of the next element of its base type and when it is decremented it
points to the memory location of the previous element of the same base type. For example,

int *x;
int *p;
p=x++;
here x and p are pointers of integer type. Pointer x is incremented by 1. Now variable p points to the memory
location next to the memory location of the pointer x. Suppose memory address of x is 2000 and as a result p will
contain memory address 2004 because integer type takes four bytes so the memory address is incremented by 4.
Incrementing the pointer results in incrementing the memory address by the number of bytes occupied by the base
type. For example,

double *x;
double *p;
p=x++;

variables x and p are pointers of double type. Pointer x is incremented by 1. Now if the memory address of x was
2000 and after incrementing p will contain memory address 2008 as double takes 8 bytes. Decrementing the pointer
results in decrementing the memory address by the number of bytes occupied by the base type. You cannot add two
pointers. No multiplication and division can be performed on pointers. Here is a program which illustrates the
working of pointer arithmetic.

#include<iostream>
using namespace std;

int main ()
{
int *x;
int *p,*q;
int c=100,a;
x=&c;
p=x+2;
q=x-2;
a=p-q;
cout << "The address of x : " << x << endl;
cout << "The address of p after incrementing x by 2 : " << p << endl;
cout << "The address of q after derementing x by 2 : " << q << endl;
cout << " The no of elements between p and q :" << a << endl;
return(0);
}

The result of the program is:-

In the program x, p and q are pointers of integer type. The statement

p=x+2;

makes p to point to the memory address which is next two memory locations apart from the location of x. The
statement

q=x-2;

makes q to point to memory address which is previous two memory locations apart from the location of x. The
statement
a=p-q;

computes the no of memory locations between p and q will come out to be 4. The statement

cout << "The address of x : " << x << endl;

prints the address of the memory location of x which is 0012FF70. The statement

cout << "The address of p after incrementing x by 2 : " << p << endl;

prints the memory address of p which comes out to be 0012FF78. Each memory location occupies 4 bytes.
Therefore after incrementing by 2, memory address is incremented by 8. The statement

cout << "The address of q after decrementing x by 2 : " << q << endl;

prints the memory address of q which is 0012FF68. After decrementing, the memory address is decremented by 8.
The statement

cout << " The no of elements between p and q :" << a << endl;

prints the no of memory locations between p and q which comes out to be 4 as p points to next two memory
locations of x and q points to the previous two memory locations of x.

Pointers and Arrays

The pointers and arrays have a very close relationship. The pointer can be set to the address of the first element of
the array. For example,

int age[];
int *p;
p=&age;
p will point to the address of the first element of the array. For example

(p+4)

will point to the fifth element of the array. Pointers are helpful where size of the array is unknown. Declaring the
array with a size of large value wastes lot of space. Pointers improve the execution time. Here is a program which
illustrates the working of arrays and pointers.

#include<iostream>
using namespace std;

int main()
{
int age[5];
int *p;
int sum=0,i;
char yes='y';
p=age;
for(i=0;i<5;i++)
{
cout << "Enter the age of a student" << endl;
cin >> *p;
sum=sum+*p;
p++;
}
p=age;
cout << "The sum of the ages" << sum << endl;\
cout << "The age of the last student is : " << *(p + 4) << endl;
return(0);
}

The result of the program is:-

The array age is of integer type. The pointer p points to the first element of the array.

p=age;

The user is allowed to enter the age of the student. The statement

cin >> *p;

stores the age of the person in contents of the array. The pointer is incremented by one memory location so that next
time age is stored in new memory location.

p++;

sum of the ages is calculated. The pointer is again referred to the address of the first element of the array. The age of
the last student cab be accessed using *(p+4) which contains the value of the 5th element of the array.
Call by Value

In the Call by Value method, the called function creates new variables to store the value of the arguments passed to
it.

The following program illustrates the invoking of a function by value:

//Program 7.4
//This function swaps the value of two variable
#include<iostream.h>
void swap(int, int);
void main()
{
int iVar1, iVar2;
cout<<"Input two numbers "<<endl;
cin>>iVar1;
cin>>iVar2;
swap(iVar1, iVar2);
cout<<"In main "<<iVar1<<" "<<iVar2<<endl;
}
void swap(int iNum1, int iNum2)
{
int iTemp;
iTemp = iNum1;
iNum1 = iNum2;
iNum2 = iTemp;
cout<<"In swap "<<iNum1<<" "<<iNum2<<endl;
}

The sample output of Program 7.4 is:


Input two numbers
15
25
In swap 25 15
In main 15 25

In Program 7.4, values entered for the variables iVar1 and iVar2 are passed to the function swap(). When the
function swap() is invoked, these values get copied into the memory locations of the parameters iNum1 and iNum2,
respectively.

This is depicted in the following figures(refer Figure 7.1 and 7.2).


iVar1 iVar2 iVar1 iVar2
15 25 15 25

15 25 25 15
iNum1 iNum2 iNum1 iNum2

Fig 7.1 When swap() Funtion Fig 7.2 After the swap()
is invokded Function is Executed

Therefore, the variables in the calling function main() are distinct from the variables in the called function swap() as
they occupy distinct memory locations.

In Program 7.4, the function arguments are passed by value. When arguments are passed by value, the called
function creates new variables of the same data type as the arguments passed to it. The values of these arguments are
copied into the newly created variables. Passing arguments by value is useful when the function does not need to
modify the values of the original variables in the calling program. Therefore, the values of the variables in the
calling functions do not get affected when the arguments are passed as values.

Reference Variable

A reference variable provides an alias- an alternate name- for the variable. A reference variable is declared by
preceding the variable name with an ampersand (&). The following statements declare a reference variable called
refer.

int num;
int &refer = num;

In the statements given above, refer is a reference variable or alias to the variable num. A reference declaration
allows a variable name and the reference name to be used interchangeably. Both the variable and its reference share
the same memory address.

The following program illustrates the use of reference variables:

//Program 7.5
//This program illustrates the use of reference variables
#include<iostream.h>
void main()
{
int number = 5;
int &ref = number;
cout<<"Number is "<<number<<endl;
cout<<"Incresing the number......"<<endl;
number++;
cout<"Number now is "<<number<<endl;
ref++;
cout<<"Reference now is "<<ref<<endl;
cout<<"Number now is "<<number<<endl;
}

In Program 7.5, the statement

number++;

increments the value of the variable number by 1, the value of the variable number therefore becomes 6. The
statement:

ref++;

again increments the value of the variable number by 1 because ref points to the same memory location as number.
The output of program 7.5 is:

Number is 5
Increasing the number........
NUmber now is 6
Reference now is 7
Number now is 7

A reference variable can be initialized only when it is declared.

Call by Reference

A reference provides an alias- an alternate name- for the variable. While passing reference arguments, a reference to
the variable in the calling program is passed.

Program 7.4 can be modified using reference arguments in the following way:

//Program 7.6
//This program swaps the values in the variable using function containing reference
arguments
#include<iostream.h>
void swap(int &iNum1, int &iNum2);
void main()
{
int iVar1, iVar2;
cout<<"Enter two numbers "<<endl;
cin>>iVar1;
cin>>iVar2;
swap(iVar1, iVar2);
cout<<"In main "<<iVar1<<" "<<iVar2<<endl;
}

void swap(int &iNum1, int &iNum2)


{
int iTemp;
iTemp = iNum1;
iNum1 = iNum2;
iNum2 = iTemp;
cout<<"In swap "<<iNum1<<" "<<iNum2<<endl;
}

Reference arguments are indicated by an ampersand (&) preceding the argument:

int &iNUm1;

In Program 7.6, the ampersand (&) indicates that iNum1 is an alias for iVar1 which is passed as an argument.

The function declaration must have an ampersand following the data type of the argument:

void swap(int &iNum1, int &iNum2)

The ampersand sign is not used during the function call:

swap(iVar1, iVar2);

The sample output of Program 7.6 is:

Enter two numbers


12
24
In swap 24 12
In main 24 12

In Program 7.6, the values in the variables iVar1 and iVar2 in the calling program are swapped.

This is depicted in Figure 7.3

iVar1 iVar2
24 12
iNum1 iNum2

Figure 7.3 After Swap() Function


is Executed

Structures.
A structure is a form of compound data type. It is an aggregate of data items of different data types. It acts as a
cluster of variables of different data types. The variables that form the structure are called members. For example,
you can have a structure of type employee which stores name, age, qualification, and telephone no and other
information about the employee under one data type. A structure can be declared as:-

struct Employee
{
char name[50];
int age;
char quali[70];
int teleno;
char info[80];
};

The keyword struct declares that Employee is a structure. The type name of the structure is Employee. The variables
declared are the members of the structure Employee. Every variable of type Employee will contain members name,
age, quali, teleno and info. The declaration of the structure is terminated by a semicolon. The data types of the
members can be of any type except the type of the structure being defined. The amount of memory need to store a
structure type is the total of the memory required by the data types of the members of the structure. The variables of
the type Employee can be declared as follows:-

struct Employee emp1; or Employee emp1;

The keyword struct is optional in C++. The variable emp1 is of type Employee. The variables of the structure can be
declared along with declaration of the structure. For example,

struct Employee
{
char name[50];
int age;
char quali[70];
int teleno;
char info[80];
}emp1,emp2;

The variables emp1 and emp2 are of type Employee. The members of the structure can be accessed using a dot
operator. The general form for accessing the member of a structure is:-
structure_name.member_name

The structure_name is the variable of type structure. The member_name is the name of the member of the structure.
For example

emp1.age=20

The variable emp1 is of type Employee and age is the member of the structure Employee. Here is a program which
illustrates the working of structures.

#include<iostream>
using namespace std;
struct Employee
{
char name[50];
int age;
char quali[70];
int teleno;
char info[80];

}emp1;

int main ()
{
Employee emp2;
cout << "Enter the name of the employee" << endl;
cin >> emp1.name;
cout << endl << "Enter the age of the employee" << endl;
cin >> emp1.age;
cout << endl << "Enter the qualification of the employee" << endl;
cin >> emp1.quali;
cout << endl << "Enter the telephone no of the employee" << endl;
cin >> emp1.teleno;
cout << endl << "Enter other information about the employee" << endl;
cin >> emp1.info;
emp2=emp1;
cout << endl << "The name of the employee : " << emp2.name << endl;
cout << "The age of the employee : " << emp2.age << endl;
return(0);
}

The result of the program is:-

The statement

struct Employee
{
char name[50];
int age;
char quali[70];
int teleno;
char info[80];

}emp1;
declares a structure of type Employee. The members of employee are name, age, quali, teleno and info. The variable
emp1 is of type Employee. The declaration ends with a semicolon. The statement

Employee emp2;

declares a variable emp2 of type employee. Members are accessed by using a dot operator. The statements

cout << "Enter the name of the employee" << endl;


cin >> emp1.name;

make the user to enter the name of the employee. The emp1.name stores the name of the employee. Similarly all the
other information is entered by the user. The statement

emp2=emp1;

assigns the information contained in emp1 of type Employee to emp2 of type Employee. Now emp2.name is same
as emp1.name and similarly all the information of emp1 is same as emp2.

Arrays of Structures

An array of structures can be declared. For example, if we want to store information about 50 employees of the
company then we can declare an array of structure of type Employee. For example,

Employee emp[100];

declares array emp of type Employee. Each variable can be accessed using an index. The index begins with zero like
other arrays. For example,

cout << "Name of the first employee" << emp[0].name << endl;

will display the name of the first employee. Similarly emp[0].age contains the age of the first employee.

Passing Structures to Functions

The structures and their members can be passed to functions. The structure and member can act as an argument for
the function. Here is a program which shows how structures are passed to functions.

#include<iostream>
using namespace std;

struct Employee
{
char name[50];
int age;
char quali[70];
int teleno;
char info[80];

}emp1;

void display(Employee emp3,char name3[50], int age2);

int main()
{
cout << "Enter the name of the employee" << endl;
cin >> emp1.name;
cout << endl << "Enter the age of the employee" << endl;
cin >> emp1.age;
cout << endl << "Enter the qualification of the employee" << endl;
cin >> emp1.quali;
cout << endl << "Enter the telephone no of the employee" << endl;
cin >> emp1.teleno;
cout << endl << "Enter other information about the employee" << endl;
cin >> emp1.info;
display(emp1,emp1.name,emp1.age);
return(0);
}

void display(Employee emp3, char name3[50],int age3)


{
cout << endl << "The name of the employee : " << name3 << endl;
cout << "The age of the employee : " << age3 << endl;
cout << "The qualification of the employee : " << emp3.quali << endl;
cout << "The telephone no of the employee : " << emp3.teleno << endl;
}

The result of the program is:-

The statement

void display(Employee emp3,char name3[50], int age2);

declares a function whose parameter are emp3 of type Employee, name3 of char type and age2 of type integer. The
statement

display(emp1,emp1.name,emp1.age);

make a call to the function display. The arguments are emp1 of type Employee, emp1.name and emp1.age which are
members of emp1. The arguments are mapped to the parameters of the function. The information of emp1 is
mapped to emp3. The members emp1.name and emp1.age are mapped to name3 and age3 respectively. The
statements

cout << endl << "The name of the employee : " << name3 << endl;
cout << "The age of the employee : " << age3 << endl;
cout << "The qualification of the employee : " << emp3.quali << endl;
cout << "The telephone no of the employee : " << emp3.teleno << endl;

display the information of emp1.

Pointers and Structures

There can be pointers to structures. Pointers are used for structures for passing structures by reference and for
creating linked lists. The structure pointers can be declared as follows:-

Employee *emp1;

Now emp1 is a pointer to the type Employee. The members of the structure using a pointer are accessed using an
arrow operator. The '->' is called an arrow operator which consists of minus sign followed by a greater than operator.
The members are accessed using arrow operator in the same way as they are accessed using a dot operator. Here is a
program which illustrates the working of pointers and structures.

#include<iostream>
using namespace std;

struct Employee
{
char name[50];
int age;
char quali[70];
int teleno;
char info[80];

}emp1;

void display(Employee *emp3);

int main()
{
cout << "Enter the name of the employee" << endl;
cin >> emp1.name;
cout << endl << "Enter the age of the employee" << endl;
cin >> emp1.age;
cout << endl << "Enter the qualification of the employee" << endl;
cin >> emp1.quali;
cout << endl << "Enter the telephone no of the employee" << endl;
cin >> emp1.teleno;
cout << endl << "Enter other information about the employee" << endl;
cin >> emp1.info;
display(&emp1);
cout << endl << "The modified age of the Employee : " << emp1.age << endl;
cout << " The modified telephone no of the Employee : " << emp1.teleno << endl;
return(0);
}

void display(Employee *emp3)


{
emp3->age=emp3->age+10;
emp3->teleno=3299574;
}

The result of the program is:-

The statement

void display(Employee *emp3);

declares a function whose parameter is a pointer of type Employee. The statement

display(&emp1);

passes the address of emp1 to the function. In the function the statements

emp3->age=emp3->age+10;
emp3->teleno=3299574;

modify the values of the member age and telephone of emp3. The member age and teleno are accessed using an
arrow operator. The age is incremented by 10 and telephone no is changed. The statements

cout << endl << "The modified age of the Employee : " << emp1.age << endl;
cout << " The modified telephone no of the Employee : " << emp1.teleno <<

print the modified age and telephone of the employee. The function alters the arguments passed as this pass by
reference.

After an introduction of structures, let us move on to discuss standard library functions.

Vous aimerez peut-être aussi