Вы находитесь на странице: 1из 68

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.

com)

Pointer in C++

55

Syllabus
Concepts of pointer (Pointer declaration, pointer operator, address operator, pointer expressions,
and pointer arithmetic), Pointers & functions (Call by value, call by reference, pointer to
functions, passing function to another function), Pointers in arrays (Searching, insertion &
deletion),Pointers to string (Searching, finding length, comparison, concatenation, reverse),
Pointers & objects (Pointers to objects, this pointer, and pointer to derived classes).

Introduction
In c++ a pointer is a variable that points to or references a memory location in
which data is stored. Each memory cell in the computer has an address that can be
used to access that location so a pointer variable points to a memory location we can
access and change the contents of this memory location via the pointer.
Basic of Pointers
Q1.What is Pointer? How pointer is declared?
Ans.A pointer is a variable that contains the memory location of another variable. In c++
a pointer is a variable that points to or references a memory location in which data is
stored. Each memory cell in the computer has an address that can be used to access
that location so a pointer variable points to a memory location we can access and
change the contents of this memory location via the pointer.
Programmer start by specifying the type of data stored in the location identified by
the pointer. The asterisk(*) tells the compiler that you are creating a pointer variable.
Finally programmer give the name of the variable.
type * variable name
Example
int *ptr;
float *string;
Q2.Describe the concept of Pointers
Ans. Computer memory is sequential collection of storage cells as shown in figure. Each
cell is commonly known as byte and has a number called as address associated with it.
Typically the addresses are numbered sequentially starting from zero. The last address
depends upon the memory size. A computer having 64KB memory will have its last
address as 65535.
Memory Cell
Address
1

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


1
2
3
.
.
.
.
.
65535
Fig. Memory Representation
Whenever we declare variable, the system allocates it somewhere in the memory. An
appropriate location holds the value of variable. Since every byte has a unique address
number, this location will have its own address number. Consider the following
statement:
int quantity=150;
This statement instructs the system complier system to find a location for integer
variable quantity and store value 150 in that location. Let us assume that the system
has chosen the address location 4096 for quantity, so it will be visualized as:
Quantity
150
4096

Variable
Value
Address

During the execution of program computer always associates the name quantity
with address 4096. We may have access to the value 150 by using either the name
quantity or the address 4096. Since memory addresses are simply numbers they can be
assigned to some variables which can be stored in memory like any other variables.
Such variables that hold memory addresses are called as pointer variables the pointer
variable is nothing but a variable that contains an address which is location of another
variable in memory.
Q3.State the use of Address operator
Ans.Once we declare a pointer variable we must point it to something we can do this by
assigning to the pointer the address of the variable you want to point as in the following
example:
Ptr = #
This places the address where num is stores into the variable ptr. If num is stored in
memory 21260 address then the variable ptr has the value 21260.
/* A program to illustrate pointer declaration*/
#include<iostream.h>
#include<conio.h>
2

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


void main()
{
int *ptr;
int sum;
sum=45;
*ptr=sum;
cout<< \n Sum is << sum;
cout<<\n The sum pointer is << ptr;
getch();
}
Q4.Program to display the contents of the variable their address using pointer
variable*/
Ans.
#include<iostream.h>
#inclide<conio.h>
void main()
{
int num, *intptr;
float x, *floptr;
char ch, *cptr;
num=123;
x=12.34;
ch=a;
intptr=&x;
cptr=&ch;
floptr=&x;
cout<<Num << *intptr << stored at address << intptr;
cout<< Value << *floptr<< stored at address <<floptr;
cout<<Character << *ctptr << stored at address << cptr;
getch();
}
Q5. Give syntax of declaring and initializing pointer.
or
Q5.Describe how to declare and initialize a pointer variable
Ans. In C++ every variable must be declared for its data type. Since pointer variables
contain addresses that belong to a separate data type they must be declared as pointers.
The declaration of pointer variable takes following form
data-type *variable-name;
The statement tells that the variable-name is a pointer variable of data-type which
will store address of the same data-type variable. For example:
int *p;
It declares the variable p as a pointer that will point to an integer data type
variable. The p can store address of another integer variable only. Similarly,
3

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


float *x;
It declares x as pointer variable a floating point type.
Initialization
The process of assigning the address of a variable to a pointer variable is known
as initialization.
For example:
int *p;
int x = 10;
p = &x;
Pointer declaration
Pointer variables are declared similar to normal variable except for addition of
unary * operator. The symbol can appear anywhere between the data type name and the
pointer variable name such as,
int *p;
other way of declarations
int *p, x, *q;
Q6. Write a simple program for accessing the data through pointer
variable.
or
Q6.How to Access variable using pointer
Ans.Once a pointer has been assigned address of a variable, the value of that variable
can be accessed using the pointer. This is done by using unary operator * (asterisk)
usually known as indirection operator, dereferencing operator or contain of operator.
For example:
int marks,*p,n;
marks=79;
p=&marks;
n=*p;
The first line declares marks and n as integer variables and p as a
pointer variable pointing to an integer.
The second line assigns value 79 to variable marks and
The third line assigns address of variable marks to pointer p.
The fourth line contains indirection operator *.
When * is placed before a pointer variable in an expression, the pointer returns value
of the variable of pointer. In above case *p returns value of variable marks because p
contains the address of marks. The * can be remembered as value at address. Thus
value of n would be 79.
p=&marks;
n=*p;
is equivalent to:
n=*&marks;
4

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Q7. Explain the concept of pointers arithmetic operations with examples.
Or Q7.Describe the Pointers Arithmetic
Ans.
1. Like other variables pointer variables can be used in arithmetic
operations. Example:
int *p, x=10;
p = &x;
*p=*p+5;
This statement with add the value 5 in the value pointed by p.
2. Integer pointers are incremented or decremented in the multiples of 2.
Similarly character by 1, float by 4 and long pointers by 8 etc.
p++; /* valid */

Fig.Example of Pointer
3. We cannot add or subtract one pointer from another. Example:
int *p1, *p2;
p1 = p1 + p2; /* invalid */
4. We can add or subtract the constant from pointer variable. In this case value of
pointer is incremented or decremented by the scaling factor of respective data
type. Example:
p = p + 2; /* valid */
Multiplication and Division on pointers
1. The value stored at pointers Address can be added or subtracted by
any constant value. Example:
*p = *p * 4; /* valid */
2. We cannot use two pointers for multiplication or division. That is,
x = x * y;
x = x / y;
is not allowed.
3. We cannot multiply or divide a pointer by constant. Example:
p = p * 4; /* invalid */
p = p / 2; /* invalid */
5

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Q8.Program to illustrate the pointer expression and pointer arithmetic
Ans.
#include<iostream.h>
#include<conio.h>
void main()
{
int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 6;
y=6*- *ptr1/ *ptr2 +30;
cout<<\nAddress of a = <<ptr1;
cout<<\nAddress of b = <<ptr2;
cout<<\n a= <<a<<\n b=<<b;
cout<< \n x=<<x <<\n y=<<y;
ptr1=ptr1 + 70;
ptr2= ptr2;
cout<< \na=<<a<< \n b=<<b;
getch();
}
Q9.State Rules for pointer operation
Ans.Following are the rules for pointer operation
1. A pointer variable can be assigned address of another variable.
2. Pointer variable can be assigned value of another pointer variable.
3. Pointer variable can be initialized by NULL value of zero value.
4. Pointer variable can be used with pre increment or decrement or post increment
or decrement operators.
5. An integer value may be subtracted or added from the pointer variable.
6. When two pointers point to the same array one pointer variable can be subtracted
from another.
7. When two pointers point to the object of same data type we can use the relational
operators to compare them.
8. Pointer variable cannot be multiplied or divided by a constant.
9. Two pointer variables cannot be added, subtracted, multiplied or divided.
10. A value cannot be assigned to any particular address. Example:
int a=20;
&a=1000; // It is illegal.
Q10.State Advantages of using Pointers
Ans.Advantage of Using Pointer
1. Pointers are most efficient in handling arrays.
2. They can be used to return multiple values from function through function
argument.
3. They permit references to functions and thereby they provide facility to pass
function as argument to another function.
6

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


4. The use of pointer arrays to character string saves the data storage space in the
memory.
5. Pointers allow C to supports dynamic memory management.
6. They provide an efficient tool for manipulating dynamic data structures such as
structures, link lists, quos, stacks, trees and graphs.
7. Pointers reduce the complexity and length of the program.
8. Pointers increase the execution speed and thus reduce the program execution
time. Of course the real power of C lies in the proper use of pointers.
Q11.Describe what is VOID and NULL pointer
Ans. void pointers
The void type of pointer is a special type of pointer. In C++, void represents the
absence of type, so void pointers are pointers that point to a value that has no type (and
thus also an undetermined length and undetermined dereference properties).
This allows void pointers to point to any data type, from an integer value or a
float to a string of characters. But in exchange they have a great limitation: the data
pointed by them cannot be directly dereferenced (which is logical, since we have no type
to dereference to), and for that reason we will always have to cast the address in the void
pointer to some other pointer type that points to a concrete data type before
dereferencing it.
One of its uses may be to pass generic parameters to a function:
// increaser
#include <iostream>
using namespace std;
void increase (void* data, int psize)
{
if ( psize == sizeof(char) )
{
char* pchar;
pchar=(char*)data;
++(*pchar);
}
else if (psize == sizeof(int) )
{
int* pint;
pint=(int*)data;
++(*pint); }
}
}
int main ()
{
char a = 'x';
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
7

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cout << a << ", " << b << endl;
return 0;
}
Output
y, 1603
sizeof is an operator integrated in the C++ language that returns the size in bytes
of its parameter. For non-dynamic data types this value is a constant. Therefore, for
example, sizeof(char) is 1, because char type is one byte long.
Null pointer
A null pointer is a regular pointer of any pointer type which has a special value that
indicates that it is not pointing to any valid reference or memory address. This value is
the result of type-casting the integer value zero to any pointer type.
int * p;
p = 0;

// p has a null pointer value

Do not confuse null pointers with void pointers. A null pointer is a value that any
pointer may take to represent that it is pointing to "nowhere", while a void pointer is a
special type of pointer that can point to somewhere without a specific type. One refers to
the value stored in the pointer itself and the other to the type of data it points to.
char *my_strcpy(char *destination, char *source)
{
char *p = destination;
while (*source != '')
{
*p++ = *source++;
}
*p = '';
return destination;
}
Pointer and Arrays
Q12. Explain use of pointers and arrays. Or
Q12. State the similarity between Pointers and arrays with example Or
Q12. Explain how array elements are accessed by using pointers.
Ans.When an array is declared the compiler allocates base address and sufficient
amount of storage memory to contain all the elements of the array in contiguous
memory location. The base address is the location first element that is 0th element of
the array. The compiler also defines the array name as a constant pointer to the first
element. For example:
int x[5] = {8, 4, 9, 6, 3};
8

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Suppose the base address of x is 9092 and assuming each integer requires 2 bytes the
five elements are stored as shown below . . . .
Index
x[0]
x[1]
x[2]
x[3]
x[4]

Value
8
4
9
6
3

Address
9092
9094
9096
9098
9100

The name x is defined as a constant pointer pointing to the first element x[0] and
therefore value of x is 9092. If we declare p as an integer pointer then we can make the
pointer p to point the array x by following assignment.
int *p;
p = &x[0];
OR
p = x;
// assigning address of array to pointer
Now we can access every value of x using p++ to move from first
element to another i. e.
p
p
p
p
p

=
=
=
=
=

&x[0];
&x[1];
&x[2];
&x[3];
&x[4];

=
=
=
=
=

9092
9094
9096
9098
9100

=
=
=
=
=

p
p++
p++
p++
p++

=
=
=
=
=

(p+0)
(p+1)
(p+2)
(p+3)
(p+4)

Therefore x[n] = *(p+n)


For initializing an array at run time:
for(i=0;i<5;i++)
cout<< *(p+i);
Q13.Program to find the average of five students using pointers */
#include<iostream.h>
main()
{
int x[5],*p, sum = 0,i;
for(i=0;i<5;i++)
cin>> x[i]);
p=x;
for(i=0;i<5;i++)
sum=sum + *(p+i);
9

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cout<<Average = << sum/5;
getch();
}
Q14.Write program to demonstrate pointer and arrays
Ans.Two dimension array using pointers
#include<stdio.h>
#include<conio.h>
void main ()
{
int a[10][10],r,c,i,j;
cout<<"Enter Rows :";
cin>>r;
cout<<"Enter Columns :";
cin>>c;
for(i=0; i < r;i++)
for(j = 0;j < c;j++)
cin>>*(a+i)+j);
for(i = 0;i < r;i++)
{
for(j=0;j<c;j++)
cout<<*(*(a+i)+j));
cout<<"\n";
}
getch();
}
Pointer and String
Q15.What is String ?How it is declared using arrays ?
Ans. A string is a sequence of characters. Any sequence or set of characters defined
within double quotation symbols is a constant string. Strings are stored in memory as
ASCII codes of characters that make up the string appended with \0(ASCII value of
null). Normally each character is stored in one byte, successive characters are stored in
successive bytes.
Character m
ASCII
77
code

y
121

Character

2
50

32

32

a
97

g
e
103 10

32

i
105

s
115

32

(
40

t
w
116 119

o
41

)
0

\0
0

The last character is the null character having ASCII value zero.
10

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


However, because strings are in fact sequences of characters, we can represent
them also as plain arrays of char elements.
For example, the following array:
char jenny [20];
is an array that can store up to 20 elements of type char. It can be represented as:

Therefore, in this array, we can store sequences of characters up to 20 characters


long. But we can also store shorter sequences. For example, jenny could store at some
point in a program either the sequence "Hello" or the sequence "Manoj Kavedia", since
both are shorter than 20 characters.
Therefore, since the array of characters can store shorter sequences than its total
length, a special character is used to signal the end of the valid sequence: the null
character, whose literal constant can be written as '\0' (backslash, zero).
Our array of 20 elements of type char, called jenny, can be represented storing
the characters sequences "Hello" and "Manoj Kavedia" as:
H

\0

\0

Initialization of null-terminated character sequences


Because arrays of characters are ordinary arrays they follow all their same rules.
For example, if we want to initialize an array of characters with some predetermined
sequence of characters we can do it just like any other array:
char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
In this case we would have declared an array of 6 elements of type char
initialized with the characters that form the word "Hello" plus a null character '\0' at the
end.
But arrays of char elements have an additional method to initialize their values: using
string literals.
These are specified enclosing the text to become a string literal between double
quotes ("). For example:
"the result is: "
is a constant string literal ..
11

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Double quoted strings (") are literal constants whose type is in fact a nullterminated array of characters. So string literals enclosed between double quotes always
have a null character ('\0') automatically appended at the end.
Therefore we can initialize the array of char elements called myword with a nullterminated sequence of characters by either one of these two methods:
char myword [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char myword [] = "Hello";
In both cases the array of characters myword is declared with a size of 6 elements
of type char: the 5 characters that compose the word "Hello" plus a final null character
('\0') which specifies the end of the sequence and that, in the second case, when using
double quotes (") it is appended automatically.
Initializing an array of characters in the moment it is being declared, and not
about assigning values to them once they have already been declared. In fact because
this type of null-terminated arrays of characters are regular arrays we have the same
restrictions that we have with any other array, so we are not able to copy blocks of data
with an assignment operation.
Assuming mystext is a char[] variable, expressions within a source code like:
mystext = "Hello";
mystext[] = "Hello";
would not be valid, like neither would be:
mystext = { 'H', 'e', 'l', 'l', 'o', '\0' };
The reason for this may become more comprehensible once you know a bit more
about pointers, since then it will be clarified that an array is in fact a constant pointer
pointing to a block of memory.
Using null-terminated sequences of characters
Null-terminated sequences of characters are the natural way of treating strings
in C++, so they can be used as such in many procedures. In fact, regular string literals
have this type (char[]) and can also be used in most cases.
For example, cin and cout support null-terminated sequences as valid
containers for sequences of characters, so they can be used directly to extract strings of
characters from cin or to insert them into cout. For example:
// null-terminated sequences of characters
#include <iostream>
using namespace std;
int main ()
{
char question[] = "Please, enter your first name: ";
char greeting[] = "Hello, ";
char yourname [80];
cout << question;
12

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cin >> yourname;
cout << greeting << yourname << "!";
return 0;
}
output
Please, enter your first name: Manoj
Hello, Manoj!
We have declared three arrays of char elements. The first two were initialized with
string literal constants, while the third one was left uninitialized. In any case, we have to
speficy the size of the array: in the first two (question and greeting) the size was
implicitly defined by the length of the literal constant they were initialized to. While for
yourname we have explicitly specified that it has a size of 80 chars.
Finally, sequences of characters stored in char arrays can easily be converted into string
objects just by using the assignment operator:
string mystring;
char myntcs[]="some text";
mystring = myntcs;
Q16.How it is declared using pointer?
Ans. Another way of accessing a contiguous chunk of memory, instead of with an array,
is with a pointer.
Since we are talking about strings, which are made up of characters, we'll be
using pointers to characters, or rather, char *str.
However, pointers only hold an address, they cannot hold all the characters in a
character array. This means that when we use a char * to keep track of a string, the
character array containing the string must already exist (having been either staticallyor dynamically-allocated).
Below is how you might use a character pointer to keep track of a string.
char label[] = "Manoj";
char label2[10] = "Kavedia";
char *labelPtr;
labelPtr = label;
We would have something like the following in memory (e.g., supposing that the
array label started at memory address 2000, etc.):
M
A
N
O
J
\0
2000
K
A
3000

\0

Note: Since we assigned the pointer the address of an array of characters, the pointer
must be a character pointer--the types must match.
Also, to assign the address of an array to a pointer, we do not use the address-of
(&) operator since the name of an array (like label) behaves like the address of that array
in this context. That's also why you don't use an ampersand when you pass a string
variable to cin.
13

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


e.g,
Q17.Describe Pointers to String can be used with example
Ans.Strings are created like character array. Therefore, they are declared and initialized
as:
char city[10] = Mumbai;
M

\0

\0

\0

\0

Compiler automatically inserts NULL character \0 at the end of a string. C


supports an alternative method to create strings using pointer variables of type char.
Such as,
char *city = Mumbai;
M

\0

This creates a string and then stores its address in the pointer variable city. This
pointer variable now points to the first character of the string. That is, the statements:
Cout << *city;
will print the current pointing character M on the screen and the statement,
Cout <<city;
will print all the sets of characters from current pointing location to the first occurrence
of \0. We can also use the runtime assignment for initializing the pointer such as,
char *city;
city = Mumbai;
This is not a string copy. It will only copy the address of first constant from array
i.e. M into the character pointer city. We can also use cin statement to initialize the
string using pointers. Example:
char *name;
cout <<Enter your name: ;
cin>> name;
cout << name;
OR
while(*name!= \0)
{
cout << *name;
name++;
}
14

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Example : Program to input the string and print it in reverse order
char *str;
int len = 0;
cout<<Enter the String: ;
cin>>str;
for( ;str!=\0;str++);
str--;
for( ;len>0;len--,str--)
cout<<<*str;
String Operation using arrays
Q18.Describe how Array of Pointers can be declared and used
Ans.We can create the array of pointers also with the same declaration of
the array. For example:
int *a[10];
in this example the array of pointers will be created i.e. the array will point to 10
different integers, such as:
a[0]=&x;
a[1]=&y;
a[2]=&z;
.
.
.
Example:
for(i=0;i<10;i++)
cin>>a[i];
for(i=0;i<10;i++)
cout << *a[i]);
Example
char nations[3][3];
This declaration says that nations is a table containing 3 names each with
maximum length of 15 characters. So, the total storage requirement for this array is 45
bytes. We know that very rarely the individual string will be of equal lengths. Therefore
instead of making each row of a fixed number of characters we can make it a pointer to
a
string of variable length.Example:
char *nations[3]={India, Australia, New Zealand};
This declares nations to be an array of three pointers each pointing to particular names
as:
name[0] India
15

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


name[1] Australia
name[2] Newzeland
This declares declaration allocates only 25 bytes of memory to store
the string. Following statement will print the strings on the screen:
for(i=0;i<3;i++)
cout << nations[i];
Q19.Write program to Find Length of string using character pointer
Ans.
/* Program to calculate Length of String */
#include <iostream.h>
#include <conio.h>
#include<stdio.h>
char line[40] ;
int calculate_length ( ) ;
void main ()
{
int length ;
cout <<" Enter a string : " ;
cin>>line ;
length = calculate_length ( ) ;
cout<<" \nThe string length is "<<length ;
getch ( ) ;
}
int calculate_length ( )
{
int count = 0 ;
while (line[count] != '\0')
{
count++ ;
}
return (count) ;
}
Q20.Write program to copy string using character array
Ans.
/* Program to Copy a String */
#include <iostream.h>
#include <conio.h>
#include<stdio.h>
void main ( )
{
int i ;
char sentence[40] , copy[40] ;
cout<<"Enter any string :" ;
16

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cin>>sentence ;
i=0;
for (i=0 ; i<40 ; i++)
copy[i] = 0 ;
i=0;
while (sentence[i] != '\0')
{
copy[i] = sentence[i] ;
i++ ;
}
cout<<"\nThe copied string is : " ;
cout<<copy ;
getch ( ) ;
}
Q21.Write program to reverse string using character array
Ans.
/* Program to perform Reversal of String */
#include <iostream.h>
#include <conio.h>
#include<stdio.h>
void main ( )
{
int count , i ;
char line[40] , reverse[40] ;
puts ("Enter A String - ") ;
cin>>line ;
count = 0 ;
while (line[count] != '\0')
count++ ;
count-- ;
for(i=0 ; i<40 ; i++)
reverse[i] = 0 ;
i=0;
while (count >= 0)
{
reverse[count] = line[i] ;
count-- ;
i++ ;
}
cout<<"\nThe reversed string is - " ;
cout<<reverse ;
getch ( ) ;
}
Q23.Write program to concatenate string using character array
Ans.
/* Program to perform Concatenation of Strings */
17

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


#include <iostream.h>
#include <conio.h>
#include<stdio.h>
void concatenate (char str1[40],char str2[40]) ;
void main ()
{
char str1[60] , str2[40] ;
cout<<"Enter the first string :" ;
cin>>str1 ;
cout<<"\nEnter the second string :" ;
cin>>str2 ;
concatenate (str1,str2) ;
cout<<"\nThe concatenated string is :" ;
cout<<str1 ;
getch ( ) ;
}
void concatenate (char str1[40], char str2[40])
{
int i, j;
i=0;
while (str1[i] != '\0')
i++ ;
str1[i] = ' ' ;
i++ ;
j=0;
while (str2[j] != '\0')
{
str1[i] = str2[j] ;
i++ ;
j++ ;
}
}
Q24.Write program to compare string using character array
Ans. /* Program to perform Comparisons of Two Strings */
#include <iostream.h>
#include <conio.h>
#include<stdio.h>
int compare (int i,char str1[],char str2[]);
void main ( )
{
int i , j , count = 0 ;
char str1[40],str2[40] ;
for (i=0 ; i<40 ; i++)
{
str1[i] = '\0' ;
str2[i] = '\0' ;
}
18

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cout<<"Enter the first string :" ;
cin>>str1;
cout<<"\nEnter the second string :" ;
cin>>str2;
count = compare (i,str1,str2);
if ( (str1[count] == '\0')&&(str2[count]=='\0'))
cout<<"\nThe two strings are equal." ;
else
cout<<"\nThe two strings are unequal." ;
getch ( ) ;
}
int compare (int i,char str1[],char str2[])
{
i=0;
whil
e ((str1[i]==str2[i])&&(str1[i]!='\0')&&(str2!='\0'))
++i ;
return (i) ;
}
Pointer to Array
Q25.Describe the concept of Pointer to arrays with example
Ans.An array is actually very much like pointer. We can declare the arrays first element
as a[0] or as int *a because a[0] is an address and *a is also an address the form of
declaration is equivalent. The difference is pointer is a variable and can appear on the
left of the assignment operator that is lvalue. The array name is constant and cannot
appear as the left side of assignment operator.
Example
/* A program to display the contents of array using pointer*/
#include<iostream.h>
#include<conio.h>
void main()
{
int a[100];
int i,j,n;
cout<<\nEnter the elements of the array\n;
cin>>&n;
cout<<Enter the array elements;
for(i=0;i<n;i++)
cin>> &a[i];
cout<<Array element are;
for(ptr=a; ptr< (a+n); ptr++)
cout<<\nValue of a[<<i<< ]=<<*ptr<< stored at address =<<ptr;
getch();
}
19

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Strings are characters arrays and here last element is \0 arrays and pointers to
char arrays can be used to perform a number of string functions.
Dynamic Memory allocation
Q26.State Disadvantages of array or static allocation
Ans. Declaring an array with a fixed size like
int arr[1000];
has two typical problems:

Exceeding maximum. Choosing a real maximum is often impossible because the


programmer has no control over the size of the data sets the user is interested in.
Erroneous assumptions that a maximum will never be exceeded are the source of
many programming bugs. Declaring very large arrays can be extremely wasteful of
memory, and if there are many such arrays, may prevent the program from
running in some systems.

No expansion. Using a small size may be more efficient for the typical data set,
but prevents the program from running with larger data sets. If array limits are
not checked, large data sets will run over the end of an array with disastrous
consequences. Fixed size arrays can not expand as needed.

These problems can be avoided by dynamically allocating an array of the right size, or
reallocating an array when it needs to expand. Both of these are done by declaring an
array as a pointer and using the new operator to allocate memory, and delete to free
memory that is no longer needed.
Q27.List the memory management operators used in c++?
Ans.There are two types of memory management operators in C++

new

delete
These two memory management operators are used for allocating and freeing memory
blocks in efficient and convenient ways
Q28.Describe new operator for dynamic memory management
Ans. The new operator in C++ is used for dynamic storage allocation. This operator can
be used to create object of any type.
General syntax of new operator in C++
The general syntax of new operator in C++ is as follows
pointer variable = new datatype;
In the above statement, new is a keyword and the pointer variable is a variable of
type datatype.
Creating Variable
int *a = new int;
20

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Here the new operator allocates sufficient memory to hold the object of datatype
int and returns a pointer to its starting point. The pointer variable a holds the address of
memory space allocated.
float *b = new float;
Here the new operator allocates sufficient memory to hold the object of datatype
float and returns a pointer to its starting point. The pointer variable a holds the address
of memory space allocated.
Example
int bobby = new int[5];
In this case, the system dynamically assigns space for five elements of type int and
returns a pointer to the first element of the sequence, which is assigned to bobby.
Therefore, now, bobby points to a valid block of memory with space for five elements of
type
int.

The first element pointed by bobby can be accessed either with the expression
bobby[0] or the expression *bobby. Both are equivalent as has been explained in the
section about pointers. The second element can be accessed either with bobby[1] or
*(bobby+1) and so on...
The most important difference is that the size of an array has to be a constant
value, which limits its size to what we decide at the moment of designing the program,
before its execution, whereas the dynamic memory allocation allows us to assign
memory during the execution of the program (runtime) using any variable or constant
value as its size.
Initializing / Assigning value
Dynamic variables are never initialized by the compiler. The assignment can be
made in either of the two ways:
First method
int *a = new int(20);
Here the new operator allocates sufficient memory to hold the object of datatype
int and returns a pointer to its starting point. The pointer variable a holds the address of
memory space allocated and initialize it to value 20;
float *f = new float(20.20);
Here the new operator allocates sufficient memory to hold the object of datatype
float and returns a pointer to its starting point. The pointer variable a holds the address
of memory space allocated and initialize it to value 20.20;
21

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Second method
The statement
*a = 45;
*b = 12.3;
assign 45 to variable of type int and 12.3 is assigned to variable of type float;
Creating Array
Single Dimension
New can be used to create a memory space for any data type including user
defined types uch as arrys , structure and classes.The general form for
int *p = new int[20];
creates a memory space for an array of 20 integers.P[0] will refer ro first element ,P[1] to
the second element and so on.
MultiDimension
While creating multidimension array with new , all the sizes must be supplied.
For example
arr_ptr = new int[30][50];
// allowed
arr_ptr = new int[35][55][15];
// allowed
arr_ptr = new int[13][15][];
//not allowed
arr_ptr = new int[][25][45];
// not allowed
the first dimension may be a variable whose value is supplied at runtime.All other must
be constant.
Q29.Describe delete operator for dynamic memory management
Ans. The delete operator in C++ is used for releasing memory space when the object is
no longer needed. Once a new operator is used, it is efficient to use the
corresponding delete operator for release of memory.
General syntax of delete operator in C++
The general syntax of delete operator in C++ is as follows:
delete pointer variable;
In the above example, delete is a keyword and the pointer variable is the pointer that
points to the objects already created in the new operator.
Example
delete pointer;
delete [] pointer
The first expression should be used to delete memory allocated for a single
element, and the second one for memory allocated for arrays of elements
Example: to understand the concept of new and delete memory management operator
in C++:
#include <iostream.h>
void main()
22

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


{
//Allocates using new operator memory space in memory for storing a
// integer datatype
int *a= new a;
*a=100;
cout << " The Output is:a="<<a;
//Memory Released using delete operator
delete a;
}
Output
The output of the above program is
The Output is:a=100
In the above program, the statement:
int *a= new a;
Holds memory space in memory for storing a integer datatype. The statement:
*a=100
Q30.List the point to be taken care while using delete
Ans.Some of the important points the programmer must note while using memory
management operators are described below:

The programmer must take care not to free or delete a pointer variable that has
already been deleted.
.
Overloading of new and delete operator is possible.
We know that sizeof operator is used for computing the size of the object. Using
memory management operator, the size of the object is automatically computed.
.
The programmer must take care not to free or delete pointer variables that have
not been allocated using a new operator.
.
Null pointer is returned by the new operator when there is insufficient memory
available for allocation.

Q31.List the similarities between malloc and new operator


Ans. The C and C++ approaches have several similarities:
- neither malloc() nor new initialize the space to zeros
- both malloc() and new return a pointer that is suitably aligned for a given
machine architecture
- both free() and delete do nothing with a NULL pointer
malloc() returns NULL if the space cannot be obtained. Many versions of new in existing
C++ compilers do likewise. However, the draft ANSI C++ standard says that a failure to
obtain storage should result in an exception being thrown or should result in the
currently installed new handler being invoked. In these newsletters we are assuming
that NULL is returned.
Q32.Write program to demonstrate new and delete operator.
23

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Ans.
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new int[i];
if (p == 0)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}
output
How many numbers would you like to type? 5
Enter number : 75
Enter number : 436
Enter number : 1067
Enter number : 8
Enter number : 32
You have entered: 75, 436, 1067, 8, 32,
String program using pointer (new and delete operator)
Q33.Write program to Find Length of string using character pointer
Ans. /* Program to calculate Length of String */
#include <iostream.h>
#include <conio.h>
#include<stdio.h>
char *line ;
int calculate_length ( ) ;
void main ()
24

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


{
int length ;
line = new line[40];
cout <<" Enter a string : " ;
cin>>line ;
length = calculate_length ( ) ;
cout<<" \nThe string length is "<<length ;
getch ( ) ;
}
int calculate_length ( )
{
int count = 0 ;
while (*(line+count) != '\0')
{
count++ ;
}
return (count) ;
}
Q34.Write program to copy string using character pointer
Ans.
/* Program to Copy a String */
#include <iostream.h>
#include <conio.h>
#include<stdio.h>
void main ( )
{
int i ;
char *sentence , *copy ;
sentence = new sentence[40];
copy = new copy[40];
cout<<"Enter any string :" ;
cin>>sentence ;
i=0;
for (i=0 ; i<40 ; i++)
*(copy+i) = 0 ;
i=0;
while (*(sentence+i) != '\0')
{
*(copy+i) = *(sentence+i) ;
i++ ;
}
cout<<"\nThe copied string is : " ;
cout<<copy ;
getch ( ) ;
}
25

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Q35.Write program to reverse string using character pointer
Ans.
/* Program to perform Reversal of String */
#include <iostream.h>
#include <conio.h>
#include<stdio.h>
void main ( )
{
int count , i ;
char *line , *reverse ;
line = new line[40];
reverse = new reverse[40];
cout<<"Enter A String - " ;
cin>>line ;
count = 0 ;
while (*(line+count) != '\0')
count++ ;
count-- ;
for(i=0 ; i<40 ; i++)
*(reverse+i) = 0 ;
i=0;
while (count >= 0)
{
*(reverse+count) = *(line+i) ;
count-- ;
i++ ;
}
cout<<"\nThe reversed string is - " ;
cout<<reverse ;
getch ( ) ;
}
Q36.Write program to concatenate string using character pointer
Ans.
/* Program to perform Concatenation of Strings */
#include <iostream.h>
#include <conio.h>
#include<stdio.h>
void concatenate (char *s1,char *s2) ;
void main ()
{
char *str1 , *str2 ;
str1 = new str1[60];
str2 = new str2[40];
cout<<"Enter the first string :" ;
cin>>str1 ;
26

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cout<<"\nEnter the second string :" ;
cin>>str2 ;
concatenate (str1,str2) ;
cout<<"\nThe concatenated string is :" ;
cout<<str1 ;
getch ( ) ;
}
void concatenate (char *s1, char *str2)
{
int i, j;
i=0;
while (*(s1+i) != '\0')
i++ ;
*(str1+i) = ' ' ;
i++ ;
j=0;
while (*(str2+j) != '\0')
{
*(str1+i) = *(str2+j) ;
i++ ;
j++ ;
}
}
Q37.Write program to compare string using character pointer
Ans. /* Program to perform Comparisons of Two Strings */
#include <iostream.h>
#include <conio.h>
#include<stdio.h>
int compare (int i,char *s1[],char *s2[]);
void main ( )
{
int i , j , count = 0 ;
char *str1,*str2 ;
str1 = new str1[60];
str2 = new str2[40];
for (i=0 ; i<40 ; i++)
{
*(str1+i) = '\0' ;
*(str2+i) = '\0' ;
}
cout<<"Enter the first string :" ;
cin>>str1;
cout<<"\nEnter the second string :" ;
cin>>str2;
count = compare (i,str1,str2);
if ( (*(str1+count) == '\0')&&(*(str2+count)=='\0'))
27

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cout<<"\nThe two strings are equal." ;
else
cout<<"\nThe two strings are unequal." ;
getch ( ) ;
}
int compare (int i,char *s1[],char *s2[])
{
i=0;
whil
e ((*(str1+i)==*(str2+i))&&(*(str1+i)!='\0')&&(*(str2)!='\0'))
++i ;
return (i) ;
}
Command Line Arguments
Q38.What is Command Line Arguments? State its use with example
Ans.In C++ it is possible to accept command line arguments. Command-line arguments
are given after the name of a program in command-line operating systems like DOS or
Linux, and are passed in to the program from the operating system. To use command
line arguments in your program, you must first understand the full declaration of the
main function, which previously has accepted no arguments. In fact, main can actually
accept two arguments:
1.
one argument is number of command line arguments (argument constant
(argc)), and
2.
the other argument is a full list of all of the command line arguments
(Argument Vector (argv))
Declaration
int main ( int argc, char *argv[] )
The integer, argc is the argument count. It is the number of arguments passed
into the program from the command line, including the name of the program.
The array of character pointers is the listing of all the arguments. argv[0] is the
name of the program, or an empty string if the name is not available. After that, every
element number less than argc is a command line argument. You can use each argv
element just like a string, or use argv as a two dimensional array. argv[argc] is a null
pointer.
Program-1
#include <iostream.h>
#include<conio.h>
int main(int argc, char *argv[])
{
int x;
cout<< \nArgument constant ="<<argc;
cout<<\n Argument Vector =;
for (x=0; x<argc; x++)
28

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cout<<\n"<<argv[x]);
return 0;
}
Q39.Write program to demonstrate command Line Arguments
Ans. Using command-line arguments.
#include <iostream.h>
#include<conio.h>
int main(int argc, char **argv)
{
cout << "Received " << argc << " arguments...\n";
for (int i=0; i<argc; i++)
cout << "argument " << i << ": " << argv[i] << endl;
return 0;
}
Output:
TestProgram Teach Yourself C++ with Manoj Kavedia
Received 7 arguments...
argumnet 0: TestProgram.exe
argument 1: Teach
argument 2: Yourself
argument 3: C++
argument 4: with
argument 5: Manoj
argument 6: Kavedia
Explanation
The function main() declares two arguments: argc is an integer that contains the
count of command-line arguments, and argv is a pointer to the array of strings. Each
string in the array pointed to by argv is a command-line argument. Note that argv
could just as easily have been declared as char *argv[] or char argv[][]. It is a matter of
programming style how you declare argv; even though this program declared it as a
pointer to a pointer, array offsets were still used to access the individual strings.
On line 4, argc is used to print the number of command-line arguments: seven in all,
counting the program name itself.
On lines 5 and 6, each of the command-line arguments is printed, passing the
null-terminated strings to cout by indexing into the array of strings.

29

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Pointer and Function
Q40.Describe the concept of pointer to function and demonstrate with example
Ans. In c++ class can be defined as follows
class MyClass
{
private:
int m_Num;
char m_Char;
public:
void getdata (int no , char ch);
void putdata();
};
Whose variable can be defined as follows
MyClass Things;
Even we can define pointer in same as normal variable is declared
MyClass *Things;
Object to pointer are useful in creating object at run time. We can also use an object
pointer to access the public member of object.Consider a class MyClass which as
defined as below
class MyClass
{
private:
int m_Num;
char m_Char;
public:
void getdata (int no , char ch);
{
m_Num = no;
m_Char = ch;
}
void putdata()
{
cout<<\n Number = <<m_Num;
cout<<\n Character =<<m_Char;
}
};
Two variable are declared of MyClass those are
MyClass Things;
// Normal Variable
MyClass *PtrThings;
// Pointer Variable
Pointer variable ptrThings is initialized with address of Things as follows
PtrThings = &Things;
Member function can be accessed using Dot Operator and the Object as follows
Things.getdata(143,M);
30

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Things.putdata();
Same members can be accessed using pointer as follows , only difference is instead of
Dot operator (.) we have to use arrow operator(->)
PtrThings->getdata(143,P);
PtrThings->putdata();
We can also create the object using pointer and new operator as follows
MyClass *ptrThings = new MyClass();
Statement with new is used to allocate memory for the data member for the data
member in the object structure and assign the address of the memory space to
ptrThings.This variable can access the member function way as show
PtrThings->getdata(143,A);
PtrThings->putdata();
Pointer and Functions
Q41.Describe call by value an call by reference technique of argument passing to
function
Ans.When an array is passed as function argument only the address of first element of
the array is passed but not the actual value of array elements.
When we pass address to a function the parameters receiving the address should
be pointers. The process of calling a function using pointers is called as call by
reference. In general when we call a function is called as call by value.
Call by Value
Example:
change(int x)
{
x=x+10;
}
void main()
{
int a=5;
change(a); //call by value
cout << a ;
}
Here function change() is called by value in the function main(). The a is the actual
parameter of the function and x is the formal parameter of the function. When the
function is called by value, the value of variable a is passed into variable x. Therefore,
it is called as call by value. The x & a are the local variables of individual functions
that is main() and change().Therefore, the changes made on variable x will not affect
variable a.
Therefore the call by value doesnt reflect the change. Instead of doing this we call
the function by reference that is by passing addresses of the variable.
The Function; which is called by reference can change value of variable used in
the call. Example:
31

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Call By Reference
change(int *x)
{
*x=*x+10;
}
main()
{
int a+5;
change(&a); // call by reference
printf(%d,a);
}
When the function change() is called, the address of variable a (not the value) is passed
into the function change(). Inside change(), variable x is declared as a pointer. Therefore
x will contain the address of variable a.
The statement:
*x = *x + 10;
means add 10 to the value stored at address of a that is x. Since x represents the
address of a, value of a is changed from 5 to 15. Therefore call by reference provides
mechanism by which the function can change the stored value in the calling function.
This mechanism is also known as call by address or pass by pointers. Example:
void swap(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
void main()
{
int a = 5, b = 10;
swap(&a, &b);
cout << \nA=<<a <<\nB= << b;
}
Example:
void copy(int *n, int *m)
{
int i;
for(i=0;i<10;i++, n++, m++)
*n = *m;
}
void main()
{
int a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int b[10];
32

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


copy(b, a); //call by reference
for(i=0;i<10;i++)
cout <<\nb[<<i<<]=<<b[i];
getch();
}
Q42.Describe what is call by value with example
Ans.The pointer are very much used in a function declaration. Sometimes only with a
pointer a complex function can be easily represented and success. The usage of the
pointers in a function definition may be classified into two groups.
1. Call by reference
2. Call by value.
Call by value
We have seen that a function is invoked there will be a link established between
the formal and actual parameters. A temporary storage is created where the value of
actual parameters is stored. The formal parameters picks up its value from storage area
the mechanism of data transfer between actual and formal parameters allows the actual
parameters mechanism of data transfer is referred as call by value. The corresponding
formal parameter represents a local variable in the called function. The current value of
corresponding actual parameter becomes the initial value of formal parameter. The value
of formal parameter may be changed in the body of the actual parameter. The value of
formal parameter may be changed in the body of the subprogram by assignment or
input statements. This will not change the value of actual parameters.
#include<iostream.h>
#include<conio.h>
void main()
{
int x,y;
x=20;
y=30;
cout<< \n Value of a and b before function call = <<a<< \t<<b;
fncn(x,y);
cout<<\n Value of a and b after function call =<<a<<\t<<b;
getch();
}
void fncn(int p, int q)
{
p=p+p;
q=q+q;
}

33

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Q43.Describe what is call by reference value with example
Ans.When we pass address to a function the parameters receiving the address should be
pointers. The process of calling a function by using pointers to pass the address of the
variable is known as call by reference. The function which is called by reference can
change the values of the variable used in the call.
/* example of call by reference*/
#include<iostream.h >
#include<conio.h>
void main()
{
int x,y;
x=20;
y=30;
cout<< \n Value of a and b before function call = <<a<< \t<<b;
fncn(&x,&y);
cout<<\n Value of a and b after function call =<<a<<\t<<b;
}
fncn(int *p, int *q)
{
*p=*p+*p;
*q=*q+*q;
}
Q44. Explain the difference between call by value and call by reference
methods for calling function.
or
Q44. Differences between Call by Value and Call by Reference
Sr.
Call by Value
Call by Reference
No.
1
The function is called by
The function is called by
directly passing value of
directly passing address of
variable as argument
variable as argument
2
We need to declare a general
We need to declare a pointer
variable as function argument
variable as argument
3
Calling function by value does
Calling function by reference
not changes actual values of
changes
actual
values
of
variables
variables
4
It is a slow way of calling It is a fast way of calling
function as we are calling it by
function as we are calling it by
passing value
passing address of a variable
5
For example:
For example:
Change(int p)
Change(int *p)
{
{
p = p + 10
*p = *p + 10
}
}
34

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Call:
Change(a);

Call:
Change(&a);

this pointer
Q45.What is this pointer ? Describe this pointer with example
Ans.The this pointer is used as a pointer to the class object instance by the member
function. The address of the class instance is passed as an implicit parameter to the
member functions
The keyword this identifies a special type of pointer. Suppose that you create an
object named x of class A, and class A has a nonstatic member function f(). If you call
the function x.f(), the keyword this in the body of f() stores the address of x. You cannot
declare the this pointer or make assignments to it.
A static member function does not have a this pointer.This is unique pointer that
is automatically passed to member function when it is called.This pointer acts as an
implicit argument to all the functions. 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
nonstatic member function is called for an object, the address of the object is passed by
the compiler as a hidden argument to the function
important points about this pointer:
this pointer stores the address of the class instance, to enable pointer access of
the members to the member functions of the class.
this pointer is not counted for calculating the size of the object.
this pointers are not accessible for static member functions.
this pointers are not modifiable.
Example of this pointer
Every class member function has a hidden parameter: the this pointer. this
points to the individual object. Therefore, in each call to GetAge() or SetAge(), the this
pointer for the object is included as a hidden parameter.
It is possible to use the this pointer explicitly, as program below illustrates.
Using the this pointer.
//
// Using the this pointer
#include <iostream.h>
class Rectangle
{
public:
Rectangle();
~Rectangle();
void SetLength(int length)
{
35

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


this->itsLength = length;
}
int GetLength() const
{
return this->itsLength;
}
void SetWidth(int width)
{
itsWidth = width;
}
int GetWidth() const
{
return itsWidth;
}
private:
int itsLength;
int itsWidth;
};
Rectangle::Rectangle()
{
itsWidth = 5;
itsLength = 10;
}
Rectangle::~Rectangle()
{
}
int main()
{
Rectangle theRect;
cout << "theRect is " << theRect.GetLength() << " feet long.\n";
cout << "theRect is " << theRect.GetWidth() << " feet wide.\n";
theRect.SetLength(20);
theRect.SetWidth(10);
cout << "theRect is " << theRect.GetLength()<< " feet long.\n";
cout << "theRect is " << theRect.GetWidth()<< " feet wide.\n";
return 0;
}
Output
theRect
theRect
theRect
theRect

is
is
is
is

10 feet long.
5 feet wide.
20 feet long.
10 feet wide.

Explanation
The SetLength() and GetLength() accessor functions explicitly use the this
pointer toaccess the member variables of the Rectangle object. The SetWidth and
36

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


GetWidth accessors do not. There is no difference in their behavior, although the
syntax is easier to understand.
If that were all there was to the this pointer, there would be little point in
bothering you with it. The this pointer, however, is a pointer; it stores the memory
address of an object. As such, it can be a powerful tool.
We donot have to worry about creating or deleting the this pointer. The compiler
takes care of that.
Pointer to Object
Q46.Describe the concept of pointer to object
Ans.A pointer is a variable which holds the memory address of another variable of nay
basic data type such as int , float , or sometime an array.A pointer can be used to hold
the address of the structure variable too.The pointer variable is very much used to
construct complex data base using the data structures such as linked list , double
linked list and binary trees.
Example
Class sample
{
private :
int x;
float y;
char s;
public :
void getdata();
void display();
};
sample *ptr;
where ptr is pointer variable that holds the address of the class object sample and
consist of the three data member such as int x , float y , and char s and also holds
member function such as getdata() and display();
The pointer to an object of class viable will be accessed and processed in on of the
following ways
(*object_name).member_name = variable ;
The parenthses are essential since the member of the class period(.) has a higher
precedence over the indirection operator(*). Or the pointer to the member of a class can
be expressed using (-) followed by greater than sign(>).This is also called as arrow(->)
operator.
Object_name->membername = variable;
Object_name->memberfunction();
Following are valid declaration of using pointer to the member of class.
Example
// Pointer to object
class student
{
private:
long int rollno;
37

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


int age;
char gender;
float height;
float weight;
public:
void getinfo()
{
cout << Roll No =;
cin >> rollno;
cout << Age =;
cin >> age;
cout << Gender =;
cin >> gender;
cout << Height =;
cin >> Height =;
cout << Weight =;
cin >> weight;
}
void disinfo()
{
cout << \n;
cout << \n Roll No =<<rollno << \n;
cout << \n Age = <<age << \n;
cout << \n Gender = << gender << \n;
cout << \n Height = << height << \n;
cout << \n Weight = << weight << \n;
}
};
// end of class definition
void main()
{
student *ptr ;
// ptr is an object of class student
cout << Enter the following information << endl;
ptr->getinfo();
cout << \n Content of class << \n;
ptr->disinfo();
getch();
}// end of main program
output
Enter the following information
Roll no : 95143
Age : 39
Gender : M
Height : 123
Weight : 84
38

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Content of clas
Roll no = 95143
Age
= 39
Gender = M
Height = 123
Weight = 84
Q47. Write program to assign some value to the member of class objects using an
indirection operator
Ans.
class student
{
private:
long int rollno;
int age;
char gender;
float height;
float weight;
public:
void getinfo()
{
cout << Roll No =;
cin >> rollno;
cout << Age =;
cin >> age;
cout << Gender =;
cin >> gender;
cout << Height =;
cin >> Height =;
cout << Weight =;
cin >> weight;
}
void disinfo()
{
cout << \n;
cout << \n Roll No =<<rollno << \n;
cout << \n Age = <<age << \n;
cout << \n Gender = << gender << \n;
cout << \n Height = << height << \n;
cout << \n Weight = << weight << \n;
}
};
// end of class definition
void main()
{
student *ptr ;
// ptr is an object of class student
39

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cout << Enter the following information << endl;
(*ptr).getinfo();
cout << \n Content of class << \n;
(*ptr).disinfo();
getch();
}// end of main program
Q48.Write a program to Demonstrate pointer to Object
Ans.
#include <iostream>
using namespace std;
class myclass
{
int i;
public:
myclass(int j)
{
i = j;
}
int getInt()
{
return i;
}
};
int main()
{
myclass ob(88), *objectPointer;
objectPointer = &ob;
cout << objectPointer->getInt();
return 0;
}

// get address of ob
// use -> to call getInt()

Q49.Write program to Demostrate pointer to Object


Ans.
// pointer to classes example
#include <iostream>
using namespace std;
class CRectangle
{
int width, height;
public:
void set_values (int, int);
int area (void) {return (width * height);
}
};
void CRectangle::set_values (int a, int b)
40

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


{
width = a;
height = b;
}
int main ()
{
CRectangle a, *b, *c;
CRectangle * d = new CRectangle[2];
b= new CRectangle;
c= &a;
a.set_values (1,2);
b->set_values (3,4);
d->set_values (5,6);
d[1].set_values (7,8);
cout << "a area: " << a.area() << endl;
cout << "*b area: " << b->area() << endl;
cout << "*c area: " << c->area() << endl;
cout << "d[0] area: " << d[0].area() << endl;
cout << "d[1] area: " << d[1].area() << endl;
delete[] d;
delete b;
return 0;
}

Pointer to Derived Class


Q50.How Pointer is used to access the derived class data members?or how pointer
can be used for derived class?
Ans.Pointer can be used to point both base class and derived class object.Pointer to
object of a base class is type-compatible with pointer to object of a derived class.hence a
single pointer variable can be made to point to objects belonging to different classes.For
example id Base is base class and Derived is a derived class from a Base class, then a
pointer declared as pointer to Base can also be a pointer Dervied.Consider the following
Base *cptr; //pointer to class B type variable
Base b;
//Base
class object
Dervied d; // derived class object
cptr = &b; // cptr point to base class object b
This is correct and valid in c++ because d is an object derived from the class
Base;But when a base class pointer used to point derive class there is problem in using
cptr(base class pointer) to access public member of derived class D. using cptr (base
class pointer) we can only access those member which are inherited from base class B
and not the member of the derived class D. Also if a member of derived class has same
name as that of member of base class then any reference to that member by cptr(base
class pointer) will always access the base class member only.
41

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Hence even if C++ permits a base pointer to point any object derived from that
base , the pointer cannot directly used to access all the member of the derived
class.Hence the only way to access those members of derived class it to declare one
more pointer to derived class.
Example of Pointer to derived class object
#include<iostream.h>
#include<conio.h>
class BaseClass
{
public:
int bs;
void show()
{
cout<< \nBase class Variable B =<<bs;
}
};
Class DerivedClass
{
public:
int ds;
void show()
{
cout<< \n Base class Variable B =<<bs;
cout<< \n Dervied class Variable D =<<ds;
}
};
void main()
{
BaseClass *bpointer;
BaseClass baseobj;
Bpointer = &baseobj;
Bpointer->bs = 1234;
cout << \n bpointer point to
bpointer->show();
DerviedClass derviedobj;
Bpointer->&derviedobj;
Bpointer->bs = 2468;

// pointer to base class


// object of base class
// Address of base class
// Access baseclass using base pointer
object of base class;
//
//
//
//

derived class
object of derived class
Address of dervied class
Access derivedclass using dervied pointer

/* bpointer->ds=3691*/
// cannot work
cout << \n bpointer now points to object of derived class;
bpointer->show();
// base pointer points derived class
42

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


derivedClass *dpointer;
// derived class pointer
dpointer-> &derivedobj;
dpointer->ds = 3691;
cout << \n dpointer point to object of derived class;
dpointer->show();
//derived pointer point derived class member
getch();
}
Output
bpointer point to object of base class
Base class Variable B = 1234
bpointer now points to object of derived class
nBase class Variable B = 2468
dpointer point to object of derived class
Base class Variable B = 2468;
Dervied class Variable D =3691
Explanation
bpointer->show(); it works because bpointer is pointer to base class hence no problem or
ambiguity in accessing it.
/* bpointer->ds=3691*/ it cannot be used because base class pointer cannot access
public member of derived class.
dpointer->show(); it works because dpointer is pointer to derived class hence no
problem or ambiguity in accessing it.
Q51.Write a program to demonstrate Pointer to Derived class object
Ans.
/*
Pointers to Derived Class Objects */
#include <iostream.h>
/*----------------------Class Interfaces-------------------------*/
class A
{
int a1;
// private data member
public :
int a2;
// public data member
void set(int);
void display();
};
class B : public A
{
int a3;
public :

// private data member


43

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


int a4;

// public data member

void set(int);
void display();

// overriding functions

};
/*----------------------Class Implementations---------------------*/
// member function definitions for class A
void A::set(int x)
{
a1 = x;
}
void A::display()
{
cout << "a1 = " << a1 << "\n";
cout << "a2 = " << a2 << "\n";
}
// member function definitions for class B
void B::set(int x)
{
a3 = x;
}
void B::display()
{
A::display();
cout << "a3 = " << a3 << "\n";
cout << "a4 = " << a4 << "\n";
}
/*----------------------Class definitions ends here---------------*/
void main(void)
{
A *base, obj1;
base = &obj1;
base->set(1);
base->a2 = 2;
cout << "Base class data members : \n";
base->display();
B obj2;
// Derived class object
base = &obj2;
base->set(10);
base->a2 = 20;
cout << "Base class data members (through subsumption) : \n";
base->display();
B *derived;
derived = &obj2;
derived->set(30);
derived->a4 = 40;
cout << "Derived class data members : \n";
derived->display();
44

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


}
Explanation
A base class A with one private data number a1 which can be initialised through
the public member function set() and a2 is the public data member. There is one more
public member function display() which displays the values of a1 and a2. This Program
then defines the derived class B. Similarly containing one public data member a4 and
private data member a3 initialised by public member function set(). Also, similar to
display function of base class A, the derived class B defines a display() function which
display for values of a3 and a4.
See that initially program defines a base class pointer ant base class object and
assigns the address of base class object obj1 to base class pointer base. Then through
the pointer to object it invokes to initialise a1 and also initialises a2 the public member
through direct assignment It then displays the values of al and a2 using public member
function display().
The program then defines a derived class pointer derived and set the address of
obj2, which is a derived class object, to it. Now obj2 can invoke its own interface and
initialises member a3 and a4 and can invokes its own member function set() and
display() which are overriding functions. This can be seen in the third set of output
values in output
String program using pointer (new and delete operator ) class and Objects
Q52.Write program to Find Length of string using character pointer
Ans. /* Program to calculate Length of String */
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <strings.h>
class StringLength
{
private:
char *str ;
int count;
StringLength ( char *s)
{
s = new char[strlen(s)+1];
strcpy(str , s);
}
void calculate_length ( )
{
int count = 0 ;
while (*(line+count) != '\0')
{
count++ ;
}
45

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


}
void displayString()
{
cout << \n String = <<str;
cout << \n Length of String =<<count;
~StringLength()
{
delete line;
}
};
void main ()
{
char *line;
line = new line[40];
cout <<" Enter a string : " ;
cin>>line ;
StringLength s1(line);
s1.calculate_length ( );
s1.displayString();
getch ( ) ;
}

Q53.Write program to copy string using character pointer


Ans.
/* Program to Copy a String */
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <strings.h>
class StringCopy
{
private:
char *str , *cstr;
int count;
StringCopy( char *s)
{
s = new char[strlen(s)+1];
strcpy(str , s);
cstr = new char[strlen(s)+1];
46

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


}
void Copy_String( )
{
while (*(str+i) != '\0')
{
*(cstr+i) = *(str+i) ;
i++ ;
}
*(cstr+i) = \0;
}
void displayString()
{
cout << \n String = <<str;
cout << \n Copied String =<<cstr;
}
~StringCopy()
{
delete str;
delete cstr;
}
};
void main ( )
{
int i ;
char *copy ;
copy = new copy[40];
cout<<"Enter any string :" ;
cin>>copy ;
StringCopy Sc1(copy);
Sc1.Copy_String(copy);
Sc1.displayString();
getch ( ) ;
}
Q54.Write program to reverse string using character pointer
Ans.
/* Program to perform Reversal of String */
/* Program to Copy a String */
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <strings.h>
class StringReverse
{
47

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


private:
char *str , *rstr;
int count,i;
StringReverse( char *s)
{
s = new char[strlen(s)+1];
strcpy(str , s);
rstr = new char[strlen(s)+1];
count= 0;
}
void Reverse_String( )
{
count = 0 ;
while (*(str+count) != '\0')
count++ ;
count-- ;
for(i=0 ; i<40 ; i++)
*((rstr+i) = 0 ;
i=0;
while (count >= 0)
{
*(reverse+count) = *(line+i) ;
count-- ;
i++ ;
}
}
void displayString()
{
cout << \n String = <<str;
cout << \n Reversed String =<<rstr;
}
~StringReverse()
{
delete str;
delete rstr;
}
};
void main ( )
{
char *line , ;
line = new line[40];
cout<<"Enter A String - " ;
48

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cin>>line ;
StringReverse SR1(line);
SR1.Reverse_String();
SR1.displayString();
getch ( ) ;
}
Q55.Write program to concatenate string using character pointer
Ans.
/* Program to perform Concatenation of Strings */
class StringConcatenate
{
private:
char *str1 , *str2;
int count,i,j;
StringConcatenate( char *s1 , char *s2 )
{
str = new char[strlen(s1)+1];
strcpy(str , s);
cstr = new char[strlen(s2)+1];
count= 0;
}
void concatenate_String ()
{
i=0;
while (*(str1+i) != '\0')
i++ ;
*(str1+i) = ' ' ;
i++ ;
j=0;
while (*(str2+j) != '\0')
{
*(str1+i) = *(str2+j) ;
i++ ;
j++ ;
}
}
void displayString()
{
cout << \n String = <<str1;
cout << \n Concatenated String =<<str2;
}
~StringReverse()
49

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


{
delete str1;
delete str2;
}
};
void main ()
{
char *st1 , *st2 ;
st1 = new st1[60];
st2 = new st2[40];
cout<<"Enter the first string :" ;
cin>>st1 ;
cout<<"\nEnter the second string :" ;
cin>>st2 ;
StringConcatenate SC1(st1, st2);
SC1.concatenate () ;
SC1.displayString();
getch ( ) ;
}
Q56.Write program to compare string using character pointer
Ans. /* Program to perform Comparisons of Two Strings */
class StringCompare
{
private:
char *str1 , *str2;
int count,i,j;
StringCompare( char *s1 , char *s2 )
{
str = new char[strlen(s1)+1];
strcpy(str , s);
cstr = new char[strlen(s2)+1];
count= 0;
}
void Compare_String ()
{
i=0;
whil
e ((*(str1+i)==*(str2+i))&&(*(str1+i)!='\0')&&(*(str2)!='\0'))
++i ;
}
void displayString()
{
cout << \n String1 = <<str1;
cout << \n String2 =<<str2;
50

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


if ( (*(str1+count) == '\0')&&(*(str2+count)=='\0'))
cout<<"\nThe two strings are equal." ;
else
cout<<"\nThe two strings are unequal." ;
}
~StringCompare()
{
delete str1;
delete str2;
}
};
void main ( )
{
int i , j , count = 0 ;
char *st1,*st2 ;
st1 = new st1[40];
st2 = new st2[40];
cout<<"Enter the first string :" ;
cin>>st1;
cout<<"\nEnter the second string :" ;
cin>>st2;
StringCompare SC1(st1,st2);
SC1. Compare_String();
SC1.displayString();
getch ( ) ;
}
Q57. Explain the meaning of following statements with reference to
pointer:
int *ptr,m
m = 8;
*ptr = m;
ptr = &m;
Ans.
1.int *ptr , m=8
Declare a pointer variable ptr and data variable m
2. m=8
data variable m which is initialized to integer value 8
3.*ptr = m
Assign the value of m ie 8 to pointer variable ptr
4.ptr = &m
assign address of variable m to pointer variable *ptr

Q58. What is the difference between myarray [3] and * (myarray + 3)?
51

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Ans. :Both will return the same element of array. Consider the following example to
understand it.
# include iostream.h
void main()
{
int myarray[]={10,20,30,40,50};
cout<<myarray[3]<<end;
cout<<*(myarray+3);
}
Explanation
The output of the above program will be 40
40. In myarray[3] we are directly
accessing the fourth element of array. And in *(myarray+3), we are using pointers
arithmetic. We are adding 3 in the base address of array which will shift it to the
address of fourth element, and by using pointer notation we are accessing the value at
that address.
Program Based on Pointer
Program Based on Pointers
Program-1.Swap values by function using pointers
#include<iostream.h>
#include<conio.h>
void swap (int*,int*);
void main ()
{
int a,b;
clrscr ( );
cout<<"value A = ";
cin>>&a;
cout<<"Value B = ";
cin>>&b;
swap(&a,&b);
cout<<"\nA = <<a;
cout<<"\nB = <<b;
getch( );
}
void swap(int *a,int *b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
52

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Program-2.Two dimension array using pointers
#include<iostream.h>
#include<conio.h>
void main ()
{
int a[10][10],r,c,i,j;
cout<<"Enter Rows :";
cin>>&r;
cout<<"Enter Columns :";
cin>>&c;
for(i=0; i < r;i++)
for(j = 0;j < c;j++)
cin>>(*(a+i)+j);
for(i = 0;i < r;i++)
{
for(j=0;j<c;j++)
cout<<*(*(a+i)+j);
cout<<"\n";
}
getch();
}
Program-4.Sorting of strings array using pointer
#include<iostream.h>
#include<conio.h>
#include<alloc.h>
#include<string.h>
void main ( )
{
int i,j,n,ln;
char *p[10], *t;
cout<<"Enter no. of names to insert :";
cin>>&n;
fflush(stdin);
t = (char *)malloc(80 * sizeof(char));
for(i = 0;i<n;i++)
{
gets(t);
ln = strlen(t)+1;
p[i] = (char *)malloc(ln * sizeof(char));
strcpy(p[i],t);
53

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


}
for(i=1;i<n;i++)
for(j=0;j<n-i;j++)
if(strcmpi(p[j],p[j+1]) > 0)
{
t = p[j];
p[j] = p[j+1];
p[j+1] = t;
}
for(i=0;i<n;i++)
cout<< \n<<p[i]);
getch();
}
Program-5.Pointer to function
#include<iostream.h>
#include<conio.h>
int pro (int(*)(int,int));
int add(int,int);
int sub(int,int);
void main ( )
{
int i,j;
clrscr( );
cout<<"\n\tAddition :-\n";
i = pro(add);
cout<<"\nA + B = "<<i;
cout<<"\n\tSubtraction :_\n";
j = pro(sub);
cout<<"A - B = <<j;
getch( );
}
int add(int a, int b)
{
return a * b;
}
int sub(int a, int b)
{
return a+b;
}
int pro(int(*p)(int,int))
{
int a,b,c;
cout<<"Enter Value for A :";
54

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cin>>&a;
cout<<"Enter Value for B :";
cin>>&b;
c = p(a,b);
return c;
}
Program-6.Factorial using Recursive function
#include<iostream.h>
#include<conio.h>
int fact(int);
void main ( )
{
int n,f;
clrscr( );
cout<<"Enter two values :";
cin>>&n;
f = fact (n);
cout<<"\nFactorial of = << n<< is =<<f;
getch();
}
int fact(int n)
{
if (n <= 1)
return 1;
else
return(n * fact(n-1));
}
Program-7.Xn using Recursive function.
#include<iostream.h>
#include<conio.h>
int power(int,int);
void main ( )
{
int x,n,e;
clrscr( );
cout<<"Enter Base values :";
cin>>&x;
cout<<"Enter Exponent's values :";
cin>>&n;
55

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


e = power (x,n);
cout<<"\nResult of <<x<<to the power <<n<< is = <<e;
getch();
}
int power(int x,int n)
{
if (n == 1)
return x;
else
return(x * power(x,n-1));
}
Program-8.Program using pointers to compute sum of all elements stored in an
array.
Ans.
#include<iostream.h>
#include<conio.h>
void main()
{
int *ptr , arr[10];
int i;
int sum=0;
ptr = arr;
for (i=0;i<=9;i++)
{
cout<<\n Enter the Number = ;
cin>>&arr[i];
}
for (i=0;i<=9;i++)
{
sum = sum + *(ptr+i);
}
cout<<\n Sum = <<sum;
getch();
}
Program-9.What will be the output of the following program?
#include<iostream.h>
void main ( )
{
float a = 13.5;
float *b, *c;
b = &a; c = b /* suppose address of a is 1006*/
cout<<&a<<b<<*(&a)<<*b;
}
Ans. 1006 1006 13.5 13.5
Program-10. Program to reverse the string using pointer.
56

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Ans.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char *str , i ,len;
// read the string
cout<<"\n Enter the string =";
cin>>str;
len = strlen(str);
//print the string in reverse order
for (i=1;i<=len;i++)
{
cout<<"\n number is = "<<*(str+len-i);
}
getch();
}
Q. Explain the meaning of following statement with reference to pointers.
int *P, X;
X = 10;
*P = X;
P = &X;
Ans. 1.int *p , x
Declare a pointer variable P and data variable x
2. X=10
data variable X which is initialized to integer value 10
3.*P = X
Assign the value of X ie 10 to pointer variable P
4.ptr = &X
assign address of variable X to pointer variable P
Program-11. Two numbers are input through keyboard into two locations C and D.
Write a program to interchange the contents of C and D.
Ans.
#include<iostream.h>
#include<conio.h>
void swap (int*,int*);
void main ()
{
int c,d;
clrscr ( );
cout<<"value c = ";
cin>>&c;
cout<<"Value d = ";
cin>>&d;
57

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


swap(&c,&d);
cout<<"\nc = "<<c;
cout<<"\nd = "<<d;
getch( );
}
void swap(int *a,int *b)
{
int *c;
// local variable
*c = *a;
*a = *b;
*b = *c;
}
Program-12. Write a program for exchanging values of two variables using call by
reference.
Ans.
#include<iostream.h>
#include<conio.h>
void swap (int*,int*);
void main ()
{
int a,b;
clrscr ( );
cout<<"value A = ";
cin>>&a;
cout<<"Value B = ";
cin>>&b;
swap(&a,&b);
cout<<"\nA = "<<a;
cout<<"\nB = "<<b;
getch( );
}
void swap(int *a,int *b)
{
int *c;
// local variable
*c = *a;
*a = *b;
*b = *c;
}
Program-13.What will be the output of the following program?
#include<iostream.h>
void main( )
{
int i = 3; int * j;
j = &i;
cout<<\n Address of i = << &i;
58

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cout<<\n
cout<<\n
cout<<\n
cout<<\n
cout<<\n
cout<<\n

Address of i = << j;
Address of j = << &j;
value of j = << j;
value of i = << i;
value of i = << *(&i);
value of i = << *j;

}
Ans. Let address of I be 65534 and address of j be 63556
Address of i =65534
Address of i =65534
Address of j = 63356
Value of j = 65534
Value of i = 3
Value of i =3
Value of i =3
Program-14.Write a program using pointer to accept an integer array and print it
in reverse order.
Ans.
#include<iostream.h>
#include<conio.h>
void main()
{
int *arr , i ;
// read the array of integers
for (i=0;i<=9;i++)
{
cout<<\n Enter the number =;
cin>>arr;
arr++;
}
//print the array in reverse order
for (i=0;i<=9;i++)
{
arr--;
cout<<\n number is = <<*arr;
}
getch();
}

Program-15
Write the program to area of rectangle using pointer to object concept , with new
and delete operator
Ans.
// pointer to classes example
59

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


#include <iostream>
using namespace std;
class CRectangle
{
int width, height;
public:
void set_values (int, int);
int area (void) {return (width * height);}
};
void CRectangle::set_values (int a, int b)
{
width = a;
height = b;
}
int main ()
{
CRectangle a, *b, *c;
CRectangle * d = new CRectangle[2];
b= new CRectangle;
c= &a;
a.set_values (1,2);
b->set_values (3,4);
d->set_values (5,6);
d[1].set_values (7,8);
cout << "a area: " << a.area() << endl;
cout << "*b area: " << b->area() << endl;
cout << "*c area: " << c->area() << endl;
cout << "d[0] area: " << d[0].area() << endl;
cout << "d[1] area: " << d[1].area() << endl;
delete[] d;
delete b;
return 0;
}
Program-16
Write a program to declare a class Account having data members as account_no
and balance. Accept and Display data for objects using pointer to the array of
objects.
Ans. :
# include <iostream.h>
#include<conio.h>
Class Account
{
int accno ;
float balance ;
public :
60

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


void getdata ( )
{
cout << \n Enter account number ;
cout <<object 1 : ;
cin >> acno. ;
count <<\n enter balance : ;
cin >> balance ;
}
void setdata (int accin)
{
accno = accin ;
balance = 0 ;
}
void set data (int accin, float balancein)
{
accon = accin ;
balance = balancein ;
}
void display ( )
{
cout << \n Account number = << accno ;
cout <<\n balance = << balance ;
}
void money-transfer (Accclass & acc, float account)
{
balance = balalnce_amount ;
acc.balance = acc.balance + amount ;
}
};
void main ( )
{
Account acc1, acc2, acc3, acc4, acc5
acc1.get data ( ) ;
acc2.set data (10) ;
acc3.set data (20, 750.5) ;
acc4.setdata (50) ;
acc5 . setdata (60) ;
cout << \n Account Information ..... ;
acc1 . display ( ) ;
acc2 . display ( ) ;
61

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


acc3 . display ( ) ;
acc4 . display ( ) ;
acc5 . display ( ) ;
int +m ;
cout <<\n How much money is to be ;
cout <<\Transfered from acc3 to acc1 : ;
cin >> +m ;
acc3 . money transfer (acc1, +m) ;
cout <<\n update information of accounts = ;
acc1 . display ( ) ;
acc2 . display ( ) ;
acc3 . display ( ) ;
acc4 . display () ;
acc5 . display ( ) ;
getch();
}
Program No -17
Write a program that counts number of vowels in a string
Ans. /* Program to calculate vowel in String */
#include <iostream.h>
#include <conio.h>
#include<stdio.h>
int calculate_Vowel ( ) ;
void main ()
{
int length ;
char *line ;
line = new line[40];
cout <<" Enter a string : " ;
cin>>line ;
calculate_Vowel (line) ;
getch ( ) ;
}
void calculate_vowel (char *str)
{
int count = 0 ;
int vowel = 0 , consonant = 0;
while (*(str+count) != '\0')
{
switch (*(str+count))
{
case a :
62

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


case
case
case
case
case
case
case
case
case

A :
e :
E :
i :
I :
o :
O :
u :
U :
vowel++;
break;
default :
consonant++;
}
cout <<\n String = <<str;
cout <<\n number of Vowel =<<vowel;
cout <<\n number of consonant =<<consonant;
}
}

Program no -18
Write a program to find sum of three number using pointer to function method
Ans.
/* Program for Pointer to Function ( with arguments ) */
#include <iostream.h>
#include <conio.h>
void main ()
{
int (*a)( double, int ); /* Pointer to Function declaration */
int function ( int a, int b , int c) ;
int result ;
clrscr () ;
a = function ;

/* Pointer to Function assignment */

result = (*a)( 12, 24, 36 ) ; /* Function call using pointer 'a' */


cout<<"Result = "<<result ;
getch () ;
}
63

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


int function ( int a, int b , int c)
{
int d;
d = a + b + c;
return ( d ) ;
}
Program no -19
Write C++ program to swap two numbers using call by value.
Ans.
/* Program to illustrates passing by value */
#include<iostream.h>
#include<conio.h>
void swap (int, int) ;
void main( )
{
int a = 11, b = 22;
cout <<"\n Before swap a = "<<a<<" and b = "<<b;
swap(a, b);
}
void swap(int x, int y)
{
//exchange the values of x and y
int temp = x;
x = y;
y = temp;
cout <<"\n After swap a = "<<x<<"and b = "<<y;
}
Program no -20
Write C++ program to swap two numbers using call by reference.
Ans.
/* Program to illustrates passing by reference */
#include<iostream.h>
#include<conio.h>
void swap (int&, int&) ;
void main( )
{
int a = 11, b = 22;
cout <<"\n Before swap a = "<<a<<" and b = "<<b;
swap(a, b);
cout <<"\n After swap a = "<<a<<"and b = "<<b;
}
void swap(int& x, int& y)
{
//exchange the values of x and y
int temp = x;
x = y;
y = temp;
}
64

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Program no -21
Write C++ program to demonstrate function argument by value method
Ans. /* Objects as Function Arguments -by value*/
#include <iostream.h>
#include<conio.h>
class Rational
{
int numerator;
int denominator;
public :
void set(int, int); // prototypes declared
void print();
void sum (Rational, Rational);
};
void Rational::set(int a, int b)
{
numerator = a;
denominator = b;
}
void Rational::print()
{
cout << numerator << " / " << denominator;
cout << "\n";
}
void Rational::sum(Rational n1, Rational n2)
// n1,n2 are objects
{
int temp = 0;
temp += n1.numerator * n2.denominator;
temp += n1.denominator * n2.numerator;
numerator = temp;
denominator = n1.denominator* n2.denominator;
}
void main(void)
{
Rational a, b, c;
clrscr();
a.set(2,5);
b.set(3,7);
c.set(0,0);
c.sum(a,b);
// Objects passed as arguments-by value
cout << "a = "; a.print();
cout << "b = "; b.print();
cout << "c = "; c.print();
getch();
}
65

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


Program no -22
Write C++ program to demonstrate function argument by reference method
Ans. /* Objects as Function Arguments -by reference*/
#include <iostream.h>
#include<conio.h>
class Rational
{
int numerator;
int denominator;
public :
void set(int, int); // prototypes declared
void print();
void exchange (Rational*);
};
void Rational::set(int a, int b)
{
numerator = a;
denominator = b;
}
void Rational::print()
{
cout << numerator << " / " << denominator;
cout << "\n";
}
void Rational::exchange(Rational *n1)
{
int temp = 0;
temp=numerator;
numerator=(*n1).numerator;
(*n1).numerator=temp;
temp=denominator;
denominator=(*n1).denominator;
(*n1).denominator=temp;
}
void main(void)
{
Rational a, b;
clrscr();
a.set(2,5);
b.set(3,7);
a.exchange(&b);
// Objects passed as arguments
cout << "a = "; a.print();
66

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


cout << "b = "; b.print();
getch();
}
Board Question Year Wise
Winter 2007
a. Can we use base class pointer for accessing member function of derived class ?
Explain with suitable example.
b. Write a program that counts number of vowels in a string
c. Differentiate between calling function by value and calling function by reference.
Give suitable examples
Summer 2008
a. Write the advantages of pointer
b. What is the scope of base class member inherited in derived class in the following
code
Class base
{
int j;
public :
1. void set(int a , int b);
}
class derived : public base
{
int k ;
public :
derived (int x);
---------------------------}
and state in how many types we can inherit properties if base class in derived
class.
c. In how many ways we can use pointer in function definition explain it
d. What do you mean by pointer?which are the pointer operator present?give its
example
e. Write a program to find sum of three number using pointer to function method
Winter 2008
a. What is dynamic binding.
b. Write a program to count number of characters in a word using pointer to string.
c. Write a program in C++ to generate a Fibonacci series of n numbers using run
time binding
d. What are rules governing the declaration of a destructor member function.
e. How to initialize a pointer? Explain with syntax
Summer 2009
a. Write C++ program to swap two numbers using call by reference.
b. Write any two applications of using pointers.
67

Prof.Manoj S.Kavedia (9860174297)(urallalone@yahoo.com)


c. Explain the role of access specifier in inheritance. Give example.
d. Write a program to find the length of a string using pointers.
Winter 2009
a. Write use of this pointer. Give example.
b. Write example of pointer to object.
c. Distinguish between call by value and call by reference method.
d. Write a program to display the string in reverse order
e. Explain command line arguments.
Summer 2010
a. What is pointer? How to declare pointer, give syntax.
b. Explain the concept of this pointer.
c. Write -a program to copy content of one string to another string using pointer to
string
d. Write a program to concatenate 2 strings using pointer to string.

68

Вам также может понравиться