Sie sind auf Seite 1von 163

Copy write by saurabh singh naruka 08440934337

Q.1 What is meant by exceptions? How an exception is handled in C++? Explain with the help of an
example.

Q1. What is C++? Explain the history of C++? Also Explain the Difference between C
and C++ ?
Answer: Released in 1985, C++ is an object-oriented programming language created by Bjarne
Stroustrup at Bell Labs. C++ maintains almost all aspects of the C language, while simplifying
memory management and adding several features - including a new datatype known as a
class to allow object-oriented programming. C++ maintains the features of C which allowed for
low-level memory access but also gives the programmer new tools to simplify memory
management.
C++ is a powerful general-purpose programming language. It can be used to create small
programs or large applications. It can be used to make CGI scripts or console-only DOS programs.
C++ allows you to create programs to do almost anything you need to do.
Difference between C and C++
C

C++

C follows procedural style


programming

C++ is Multi-Paradigm ( not pure OOP,


supports both procedural and object
oriented)

C data security is less

In C++ we can use modifiers for our class


members to make it inaccessible from
outside.

C follows top-down approach


( solution is created in step by step
manner, like each step is
processed into details as we
proceed )

C++ follows a bottom-up approach ( where


base elements are established first and are
linked to make complex solutions )

C does not support function


overloading

C++ supports function overloading

C doesnt allows use of functions in

C++ allows use of functions in structures


1

Copy write by saurabh singh naruka 08440934337

structures
C Doesnt supports reference
variables

C++ supports reference variables ( two


variables can point to same memory
location )

C does not have a built in


exception handling framework,
though we can emulate it with
other mechanism.

C++ directly supports exception handling

-------------------------------------------------------------------------------------Q2. What are the basics concepts of OOP?


Answer: Following are the basic elements of Object oriented programming(OOPS)
Classes : Classes are data types based on which objects are created. Objects with
similar properties and methods are grouped together to form a Class. Thus a Class
represents a set of individual objects. Characteristics of an object are represented in a
class as Properties. The actions that can be performed by objects become functions of the
class and is referred to as Methods. Class can be considered as a blueprint of a
building, you can not stay inside blueprint of building, you need to construct
building(s) out of that plan. You can create any number of buildings from the
blueprint, similarly you can create any number of objects from a class.
class Vehicle
{
public:
int a;
double b;
void show()
{
//code write here
}
};
Objects: Object is the basic unit of object oriented programming. An Object is a
collection of data members and associated member functions also known as
methods. An object represents a particular instance of a class. There can be more than
one instance of an object. Each instance of an object can hold its own relevant data. It is

Copy write by saurabh singh naruka 08440934337

important to remember that whenever a class is created an object of that class


should be created. without creating object we cant able to use that class.
From the above example, we can create instance of class bird as given below
Example:

Bird birdobject;

Encapsulation: Encapsulation is the mechanism by which data and associated


operations/methods are bound together and thus hide the data from outside world. In
other words we can say that .The wrapping up of data and its functions into a single
unit is called Encapsulation.
It's also called data hiding. When using Data
Encapsulation, data is not accessed directly, it is only accessible through the functions
present inside the class. In c++, encapsulation achieved using the access specifiers
(private, public and protected). Data members will be declared as private (thus protecting
from direct access from outside) and public methods will be provided to access these
data. Consider the below class
class student
{
private:
int age;
public:
int getAge()
{
return age;
}
int setAge(int value)
{
if(value > 0)
{
age = value;
}
3

Copy write by saurabh singh naruka 08440934337

}
};
In the class Student, access to the data field age is proptected by declaring it as private
and providing public accessor methods. What would have happened if there was no
accessor methods and the field age was public? Anbody who has a Student object can
set an invalid value (negative or very large value) for the age field. So by encapsulation
we can preveting direct access from outside, and thus have complete control, protection
and integrity of the data.
Data abstraction: Data abstraction refers to hiding the internal implementations
and show only the neccessery details to the outside world. For example, a
database system hides certain details of how data is stored and created and maintained.
Similar way, C++ classes provides different methods to the outside world without giving
internal detail about those methods and data. In C++ data abstraction is implemented
using interfaces and abstract classes.
Example:
class Stack
{
public:
virtual void push(int)=0;
virtual int pop()=0;
};
class MyStack : public Stack
{
private:
int arrayToHoldData[]; //Holds the data from stack
public:
void push(int) {
// implement push operation using array
}
int pop(){
// implement pop operation using array
}
};
In the above example, the outside world only need to know about the Stack class and its
push, pop operations. Internally stack can be implemented using arrays or linked lists or
4

Copy write by saurabh singh naruka 08440934337

queues or anything that you can think of. This means, as long as the push and pop
method performs the operations work as expected, you have the freedom to change the
internal implementation with out affecting other applications that use your Stack class.
Inheritance: Inheritance allows one class to inherit properties of another class.
Inheritance is the one of the very important concepts in C++/OOP. It helps to modularise
the code, improve reusability and reduces tight coupling between components of the
system. Inheritance helps in reducing the overall code size of the program. As the name
suggests Inheritance allows one class to inherit properties of another class. In other
words, Inheritance is the process of forming a new class from an existing class
called as base class, new class is formed called as derived class. The ":" operator is
used for inheriting a class.
class Shape
{
public:
int getSize()
{
return size;
}
void setSize(int w)
{
size = w;
}
protected:
int size;
};
// Derived class
class Square: public Shape
{
public:
int getArea()
{
return (size * size);
}
};

In the above example, class Square inherits the properties and methods of class Shape.
Following are the different types of inheritance followed in C++.

Single inheritance
Multiple inheritance

Hierarchial inheritance

Multilevel inheritance
5

Copy write by saurabh singh naruka 08440934337

Hybrid inheritance

Polymorphism: The ability to use an operator or function in different ways in


other words giving different meaning to operators or functions is called polymorphism.
Poly refers to many. That is a single function or an operator functioning in many ways
different upon the usage is called polymorphism.
Type of polymorphism:
(i) Compile time polymorphism : In this method object is bound to the function call at the
compile time itself.
(ii) Run time polymorphism : In this method object is bound to the function call only at
the run time.
Example:
#include <iostream.h>
class Value
{
protected:
int val;
public:
void set_values (int a)
{ val=a;}
};
class Cube: public Value
{
public:
int cube()
{ return (val*val*val); }
};
6

Copy write by saurabh singh naruka 08440934337

int main () {
Cube cb;
Value * ptr = &cb;
ptr->set_values (10);
cout << "The cube of 10 is::" << cb.cube() << endl;
return 0;
}
Result:
The cube of 10 is:: 1000
In the above OOPs example "Cube" is a derived class of "Value". To implement
polymorphism a pointer "ptr" is used to reference to the members of the class "Cube".
This is an example for "Compile time polymorphism."
Overloading: Overloading is one type of Polymorphism. It allows an object to have
different meanings, depending on its context. When the exiting operator or function is
made to operate on new data type, or class it is said to be overloaded.
Message Passing : It refers to that establishing communication between one place to
another. Message Passing is nothing but sending and receiving of information by
the objects same as people exchange information. So this helps in building systems that
simulate real life. Following are the basic steps in message passing.

Creating classes that define objects and its behavior.


Creating objects from class definitions

Establishing communication among objects

In OOPs, Message Passing involves specifying the name of objects, the name of the
function, and the information to be sent.
-----------------------------------------------------------------------------------------------Q3. What is object-oriented programming? How is it different from the
procedure oriented programming? Also explain How is OOP implement in C++?
7

Copy write by saurabh singh naruka 08440934337

Answer: Object Oriented programming: Object-oriented programming (OOP) is a programming

paradigm that uses Objects and their interactions to design applications and computer
programs. OOP is a better way of solving computer problems compared to a procedural
programming language such as C .The main aim/purpose of object oriented programming is to
increase the flexibility, maintainability of programs and most importantly debugging a program.
Because programs created using an OO language are modular, they can be easier to develop, and
simpler to understand after development. So to modify a particular data, it is easy to identify
which function to use. OOP uses classes which contain members (variables) and methods
(functions). OOP uses a modular type of programming structure. OOP is a type of programming in
which programmers define not only the data type of a data structure, but also the types of
operations that can be applied to the data structure. In this way, the data structure becomes an
object that includes both data and functions. In addition, programmers can create relationships
between one object and another. For example, objects can inherit characteristics from other
objects. One of the main advantages of object-oriented programming over procedural
programming is that they enable programmers to create modules that do not need to be changed
when a new type of object is added. A programmer can simply create a new object that inherits
many of its features fro existing objects. This makes object-oriented programs easier to modify.
An object-oriented application uses a collection of objects, which communicate by passing
messages to request services. Objects are capable of passing messages, receiving messages, and
processing data. OOP uses objects as its fundamental building blocks. Each object is an instance
of some class. Classes allow the mechanism of data abstraction for creating new data types .
Inheritance allows building of new classes from existing classes. Hence if any of these elements
are missing in a program we cannot consider that program as objected oriented program.
Advantages of Object oriented programming:
Modularity: The source code for a class can be written and maintained independently of
the source code for other classes. Once created, an object can be easily passed around
inside the system.
Information-hiding: By interacting only with an object's methods, the details of its
internal implementation remain hidden from the outside world.

Code re-use: If a class already exists, you can use objects from that class in your
program. This allows programmers to implement/test/debug complex, task-specific objects,
which you can then use in your own code.

Easy Debugging: If a particular object turns out to be a problem, you can simply remove
it from your application and plug in a different object as its replacement. This is analogous
to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the
entire machine.

Software complexity can be easily managed


It is quite easy to partition the work in a project based on object

Features of OOPs are the following:


Object-: An object is an identifiable entity with some characteristics and behavior.
8

Copy write by saurabh singh naruka 08440934337

Class-: A class represents a group of objects that share common properties, behavior and
relationships.
Data Abstraction-: Abstraction refers to act of representing essential features without including
the background details or explanations.
Encapsulation-: The wrapping up of data and associated functions into a single unit is known as
Encapsulation. Encapsulation implements data abstraction.
Inheritance-: It is the capability of one class of things to inherit capabilities or properties from
another class.
Polymorphism-: It is the ability for a message or data to be processed in more than one form.
Polymorphism is implemented in C++ through virtual functions and overloading- function
overloading and operator overloading.
Difference Between Procedure Oriented Programming (POP) & Object Oriented
Programming (OOP)

Divided Into

Importance

Approach

Access
Specifiers

Data Moving

Procedure oriented
programming

Object Oriented Programming

In POP, program is divided into

In OOP, program is divided into parts called

small parts called functions.

objects.

In POP,Importance is not given to

In OOP, Importance is given to the data rather

data but to functions as well as

than procedures or functions because it works

sequence of actions to be done.

as a real world.

POP follows Top Down approach.

OOP follows Bottom Up approach.

POP does not have any access

OOP has access specifiers named Public,

specifier.

Private, Protected, etc.

In POP, Data can move freely from

In OOP, objects can move and communicate

Copy write by saurabh singh naruka 08440934337

Expansion

Data Access

function to function in the system.

with each other through member functions.

To add new data and function in

OOP provides an easy way to add new data and

POP is not so easy.

function.

In POP, Most function uses Global

In OOP, data can not move easily from function

data for sharing that can be

to function, it can be kept public or private so we

accessed freely from function to

can control the access of data. So Concept of

function in the system. , So there

Data hiding prevents accidental change in

are possibilities of accidental

the data

change in data.

Data Hiding

Overloading

POP does not have any proper way

OOP provides Data Hiding so provides more

for hiding data so it is less secure.

security.

In POP, Overloading is not possible.

In OOP, overloading is possible in the form of


Function Overloading and Operator
Overloading.

Examples

Example of POP are : C, VB,

Example of OOP are : C++, JAVA, VB.NET,

FORTRAN, Pascal.

C#.NET.

Implement OOP in C++ : A class binds together data and its associated function under
one unit thereby enforcing encapsulation. The private and protected member remain
hidden from outside world. Thus a class enforces data hiding. The outside world is given
only the essential information through public members, thereby enforcing abstraction.
------------------------------------------------------------------------------------------------

10

Copy write by saurabh singh naruka 08440934337

Q4. What are the main characteristics of an object oriented programming ? Compare Them
with the structured programming?
Answer:
Characteristics of OOPs:
i.

Emphasis on data rather than procedure.

ii.

Programs are divided into what are known as objects.

iii. Function and data are tied together in a data structure.


iv. Data is hidden and cannot be accessed by external functions.
v.
vi.
vii.

Objects may communicate with classes through functions.


New data and functions can be easily added whenever necessary.
Follows bottom up approach in program design.

Some other characteristics included in C++:


a.

Ability to declare variable anywhere.

b.
New data types like long long int, Boolean and complex data type to denote complex
numbers.
c.

New header file such as stdbool.h, inttypes.h.

d.

C++ supports exceptional handling for handling errors.

e.

C++ introduced new keywords like new, delete, inline, public, private, this etc.

-----------------------------------------------------------------------------------------------Q5: What is array? Also explain the type of array with example?
Answer: Array is a group of elements of same type referred using a unique name. Each element of
an array are stored in memory locations indexed from 0 through n number of its elements. The
lowest indexed will be the first element and highest indexed the last element of an array. Just like
variables, we have to declare arrays before using them. The general syntax for declaring an array
is
Syntax:

type array_name[array size]


11

Copy write by saurabh singh naruka 08440934337

In the above syntax the "type" defines the data type, "array_name" defines the unique name,
"array size" defines the number of elements contained in an array even if the size is not specified
the C++ compiler counts the size.
Array are classified into three major types they are single dimensional, two dimensional, multi
dimensional arrays.
(i) Single / One Dimensional arrays: Single Dimensional Array is an array having a single
index value to represent the arrays element.
Syntax:

type array_name[array_size_1]
Example:
int Age[5] ;
float cost[30];

Initialization of One Dimensional Array: An array can be initialized along with declaration. For
array initialization it is required to place the elements separated by commas enclosed within
braces.
Example:
int A[5] = {11,2,23,4,15};
It is possible to leave the array size open. The compiler will count the array size.
Example:

12

Copy write by saurabh singh naruka 08440934337

int B[] = {6,7,8,9,15,12};


C++ Simple array program to print array value.
#include <iostream>
#include <conio>
void main()
{

int a[5] = {1,2,3,4,5};


cout<<a[0];
getch();
}

output: 1

(ii) Two Dimensional array: Two Dimensional Array is a simple form of multi-dimensional array
that stores the array elements in a row, column matrix format.
Syntax:

type array_name[array_size1][array_size2]
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
Example:
int a[3][4];
In above example A two-dimensional array can be think as a table, which contains 3 rows and 4
columns. Can be shown as below:

13

Copy write by saurabh singh naruka 08440934337

Initializing Two-Dimensional Arrays:


Multi dimensioned arrays may be initialized by specifying bracketed values for each row. Following
is an array with 3 rows and each row have 4 columns.

int a[3][4] = {
{0, 1, 2, 3} ,

/* initializers for row indexed by 0 */

{4, 5, 6, 7} ,

/* initializers for row indexed by 1 */

{8, 9, 10, 11}

/* initializers for row indexed by 2 */

};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

C++ 2D array program to print array values.


#include <iostream>
#include<conio.h>
void main ()
{
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

14

Copy write by saurabh singh naruka 08440934337

for ( int i = 0; i < 5; i++ )


{
for ( int j = 0; j < 2; j++ )
{
cout << " a[" << i << "][" << j << "]: ";
cout << a[i][j];
}
cout<<endl;
}
getch();
}

output:
a[0][0]: 0 a[0][1]: 0
a[1][0]: 1 a[1][1]: 2
a[2][0]: 2 a[2][1]: 4
a[3][0]: 3 a[3][1]: 6
a[4][0]: 4 a[4][1]: 8

(iii) Multi Dimensional Array :The Multi Dimensional Array is an array with two or more index
values. It is also known as array of arrays. A two dimensional array is also a multi dimensional
array.
Syntax:

type array_name[array_size_1][array_size_2]...[array_size_n]

Example: the following declaration creates a three dimensional 5 . 10 . 4 integer array:


int threedim[5][10][4];
Example:
15

Copy write by saurabh singh naruka 08440934337

#include <iostream.h>
void main()
{
int i,j;
char a[2] [2] = {'A','B','C','D'};
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout << "Row:: "<< i+1 << "s column::"<<
j+1 <<" element is:: "<< a[i][j]<< '\n';
}
}
}

Result:
Row:: 1s column::1 element is :: A
Row:: 1s column::2 element is :: B
Row:: 2s column::1 element is :: C
Row:: 2s column::2 element is :: D
--------------------------------------------------------------------------------------------------------------------

Q6. How to passing array as parameters in C++? What is passing by reference?


Answer: In C++ while passing array as parameters only the address of the array element is
passed. So it is "passing by reference" so that the actual array element will get changed. Even
though the array is passed as reference "&" symbol is not used instead the "[]" is used to in the
parameter name.

16

Copy write by saurabh singh naruka 08440934337

To accept an array as parameter for a function, the parameters can be declared as the array type,
but with empty brackets, omitting the actual size of the array. For example:

int sum(int a[])


This function accepts a parameter of type "array of int" called a. In order to pass to this function
an array declared as:

int arr[5];
it would be enough to write a call like this:

sum(arr);
Example: C++ program to pass an array as parameter.
#include <iostream.h>
#include <iomanip.h>
int sum(int[]);
void main()
{
int arr[5] = {1,3,5,2,5};
cout << "Sum of the array elements is: " << sum(arr);
}
int sum(int a[])
{
int x = 0;
int i;
for (i = 0; i < 5; i++)
{
x += a[i];
}
17

Copy write by saurabh singh naruka 08440934337

return x;
}
Output:
Sum of the array elements is: 16

Passing 2D array as Parameters:


Two-dimensional arrays can be passed as parameters to a function, and they are passed by
reference. When declaring a two-dimensional array as a formal parameter, we can omit the size of
the first dimension, but not the second; that is, we must specify the number of columns. For
example:
void fun(int a[ ][3],int n, int m)
In order to pass to this function an array declared as:
int arr[4][3];

we need to write a call like this:


fun(arr);

Example: C++ program to pass 2D array as parameter.


#include <iostream.h>
#include <conio.h>
void fun(int a[ ][3],int n, int m)
{
for (int i = 0; i < n; i++)
for (int j = 0; i < m; j++)
cout << A[i][j];
}
int main ()
{
18

Copy write by saurabh singh naruka 08440934337

int arr[4][3] ={ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };
fun(arr,4,3);
getch();
return 0;
}

output
1

10 11 12

--------------------------------------------------------------------------------Q7. Write short notes on:


(i)

Array of Objects

(ii)

Array of Strings (iii) array of pointers

Answer: (i) Array of Objects : Arrays of variables of type "class" is known as "Array of

objects". The "identifier" used to refer the array of objects is a user defined data type.
Example:
#include <iostream.h>
const int MAX =100;
class workers
{
private:
int salary;
float roll;

19

Copy write by saurabh singh naruka 08440934337

public:
void getname( )
{
cout << "\n Enter the Salary:";
cin >> salary;
cout << "\n Enter the roll:";
cin >> roll;
}
void putname( )
{
cout << "Employees" << salary <<
"and roll is" << roll << '\n';
}
};
void main()
{
workers det[MAX];
int n=0;
char ans;
do{
cout << "Enter the Employee Number::" << n+1;
det[n++].getname;
cout << "Enter another (y/n)?: " ;

20

Copy write by saurabh singh naruka 08440934337

cin >> ans;


} while ( ans != 'n' );
for (int j=0; j<n; j++)
{
cout << "\nEmployee Number is:: " << j+1;
det[j].putname( );
}
}

Output:
Enter the Employee Number:: 1
Enter the Salary:20
Enter the roll:30
Enter another (y/n)?: y
Enter the Employee Number:: 2
Enter the Salary:20
Enter the roll:30
Enter another (y/n)?: n

In the above example an array of object "det" is defined using the user defined data type
"Workers". The class element "getname()" is used to get the input that is stored in this array of
objects and putname() is used to display the information.
(ii) Array of Strings : Array of strings in C++ is used to store a null terminated string which is
a character array. This type of array has a string with a null character at the end of the string.
Usually array of strings are declared one character long to accommodate the null character.
Example:

21

Copy write by saurabh singh naruka 08440934337

int i;
string arr[10]={"AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH","III","JJJ"};
for(i=0;i<10;i++)
{
cout<<arr[i]<<endl;
}

(iii) array of pointers: There may be a situation, when we want to maintain an array, which can
store pointers to an int or char or any other data type available. Following is the declaration of an
array of pointers to an integer:
int *ptr[MAX];
This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a
pointer to an int value. Following example makes use of three integers which will be stored in an
array of pointers as follows:
Example:
#include <iostream.h>
#include<conio.h>
const int MAX = 3;
void main ()
{
int a[MAX] ={10, 20, 30};
int *ptr[MAX];
for (int i = 0; i < MAX; i++)
{
ptr[i] = &a[i]; // assign the address of integer.
}
for (int i = 0; i < MAX; i++)
{
cout << "Value of a[" << i << "] = ";
cout << *ptr[i] << endl;
}

22

Copy write by saurabh singh naruka 08440934337

getch();
}

Output:
Value of a[0] = 10
Value of a[1] = 20
Value of a[2] = 30

-----------------------------------------------------------------------------Q8. What is Control Statement? Explain.


Answer: Control Structures are statements that change the flow of a program to a different
code segment based on certain conditions. The control structures are categorized into three major
Conditional types they are
(i) Selection/branching Statements
(ii) Looping or Iteration statements
(iii) Jump Statements
Selection Statements:

If statement
If Else Statement

If Else If statement

Nested If statement

Switch statement

(i) if statement: In this control statement if the if condition is true, statement is executed;
otherwise it is skipped. The statement may either be a single or compound statement.
syntax of the if statement:
if (condition)

23

Copy write by saurabh singh naruka 08440934337

{
statement(s);
}

if example:
if (x == 100)
cout << "x is 100";

(ii) if else statement: In this control statement the given condition is evaluated first. If the
condition is true, statement1 is executed. If the condition is false, statement2 is executed. It
should be kept in mind that statement1 and statement2 can be single or compound statement.
syntax of the if - else statement:
if (condition)
statement1;
else
statement2;

24

Copy write by saurabh singh naruka 08440934337

if else example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";

(iii) If Else If or else if ladder statement:


syntax of if-else-if statement:
if(condition 1)
statement 1;
else if (condition 2)
statement2;
else
statement3;

if-else-if example:
25

Copy write by saurabh singh naruka 08440934337

if(percentage>=60)
cout<<"Ist division";
else if(percentage>=50)
cout<<"IInd division";
else if(percentage>=40)
cout<<"IIIrd division";
else
cout<<"Fail" ;

Nested if statement: The if block may be nested in another if or else block. This is called nesting
of if or else block.
syntax of the nested if statement:
if(condition 1)
{
if(condition 2)
{
statement(s);
}
}

Example:
//Write a program in c++ to find the greater number among three numbers.
#include<iostream.h>
#include<conio.h>
void main()
26

Copy write by saurabh singh naruka 08440934337

{
int a,b,c;
cout<<"enter value of a,b,c";
cin>>a>>b>>c;
if(a>b)
{
if(a>c)
{
cout<<"a is greater";
}
else
{
cout<<"c is greater";
}
}
else
{
if(b>c)
{
cout<<"b is greater";
}
else
{
cout<<"c is greater";
}
}
getch();
}
switch statement: The if and if-else statements permit two way branching whereas switch
statement permits multiple branching. The
syntax of switch statement is:
switch (var / expression)
{
case constant1 : statement 1;
break;
case constant2 : statement2;
break;
27

Copy write by saurabh singh naruka 08440934337

.
.
default: statement3;
break;
}

Example:
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
clrscr();
cout<<"select the case";
cin>>i;
switch(i)
{
case 1:
cout<<"sunday";
break;
case 2:
cout<<"monday";
break;
case 3:
cout<<"tuesday";
28

Copy write by saurabh singh naruka 08440934337

break;
default:
cout<<"wrong choice";
break;
}
getch();
}

Output: select the case 2


monday
The execution of switch statement begins with the evaluation of expression. If the value of
expression matches with the constant then the statements following this statement execute
sequentially till it executes break. The break statement transfers control to the end of the switch
statement. If the value of expression does not match with any constant, the statement with
default is executed.
Some important points about switch statement:
The expression of switch statement must be of type integer or character type.
The default case need not to be used at last case. It can be placed at any place.
The case values need not to be in specific order.
Looping statement: It is also called a Repetitive control structure. Sometimes we require a set
of statements to be executed a number of times by changing the value of one or more variables
each time to obtain a different result. This type of program execution is called looping. In C++ the
looping statement are categorized into three types they are :
while loop
do-while loop
for loop

29

Copy write by saurabh singh naruka 08440934337

While loop: In the while loop a condition is first evaluated. If the condition is true, the loop body
is executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly as long
as the condition remains true. As soon as the condition becomes false, it comes out of the loop
and goes to the statement next to the while loop.
Syntax of while loop
while(condition)
{
statement(s);
}

Example:
#include<iostream.h>
#include<conio.h>
void main()
{
int i = 1;
clrscr();
while(i<=10)
{
Cout<<i;
i++;
}
getch();
}

30

Copy write by saurabh singh naruka 08440934337

output:
1 2 3 4 5 6 7 8 9 10

do-while loop: The do-while loop is similar to while loop but one important difference between
the while loop and the do-while loop is the relative ordering of the conditional test and loop body
execution. In the while loop, the loop repetition test is performed before each execution the loop
body; the loop body is not executed at all if the initial test fail. In the do-while loop, the loop
termination test is performed after each execution of the loop body. Hence, the loop body is
always executed least once.
Syntax of do-while loop
do
{
statements;
} while (condition);

Example:

31

Copy write by saurabh singh naruka 08440934337

#include<iostream.h>
#include<conio.h>
void main()
{
int i = 1;
clrscr();
do
{
Cout<<i;
i++;
}while(i<=10);
getch();
}
output:
1 2 3 4 5 6 7 8

9 10

32

Copy write by saurabh singh naruka 08440934337

for loop: It is a count controlled loop in the sense that the program knows in advance how many
times the loop is to be executed.

syntax of for loop

for (initialization; decision; increment/decrement)


{
statement(s);
}

Example:

33

Copy write by saurabh singh naruka 08440934337

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();

for(int i = 1 ; i <= 10 ; i++)


{
Cout<<i;
}
getch();
}

output:
1 2 3 4 5 6 7 8 9 10

In for loop three operations take place:


Initialization of loop control variable
Testing of loop control variable
Update the loop control variable either by incrementing or decrementing.

Initialization operation is used to initialize the value. On the other hand, Decision operation is used
to test whether the condition is true or false. If the condition is true, the program executes the
body of the loop and then the value of loop control variable is updated. Again it checks the
condition and so on. If the condition is false, it gets out of the loop.

34

Copy write by saurabh singh naruka 08440934337

Jump Statements: The jump statements unconditionally transfer program control within a
function. In C++ the Jump statement are categorized into three types they are :

goto statement
break statement
continue statement

The goto statement: goto allows to make jump to another point in the program.
The general format is:

goto end;

35

Copy write by saurabh singh naruka 08440934337

end: end is known as label. It is a user defined identifier. After the execution of goto statement,
the control transfers to the line after label pqr.

Example:

#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
cout<<"enter the value of a";
cin>>a;
cout<<"enter the value of b";
cin>>b;
if(a>b)
{
goto statement1;
}
else
{
goto statement2;
}
statement1:
cout<<"greater number is

"<<a;

goto end;
36

Copy write by saurabh singh naruka 08440934337

statement2:
cout<<"greater number is

"<<b;

end:
getch();
}

output:
enter the value of a5
enter the value of b2
greater number is 5
The break statement: The break statement, when executed in a switch structure, provides an
immediate exit from the switch structure. Similarly, you can use the break statement in any of the
loop. When the break statement executes in a loop, it immediately exits from the loop.

#include<iostream.h>
#include<conio.h>
void main()
{
for(int i = 1; i <=10;i++)
{
if(i == 6)
{
cout<<"i like 6";
break;
37

Copy write by saurabh singh naruka 08440934337

}
cout<<"the value of i is "<<i<<endl;
}
getch();
}

the value of i is 1
the value of i is 2
the value of i is 3
the value of i is 4
the value of i is 5
i like 6

The continue statement : The continue statement is used in loops and causes a program to skip
the rest of the body of the loop starts a new iteration.
while (condition)
{
Statement 1;
If (condition)
continue;
statement;
}

#include<iostream.h>
#include<conio.h>
38

Copy write by saurabh singh naruka 08440934337

void main()
{
for(int i = 1; i <=10;i++)
{
if(i == 6)
{
cout<<"i like 6"<<endl;
continue;
}
cout<<"the value of i is "<<i<<endl;
}
getch();
}

output:
the value of i is 1
the value of i is 2
the value of i is 3
the value of i is 4
the value of i is 5
i like 6
the value of i is 7
the value of i is 8
the value of i is 9
39

Copy write by saurabh singh naruka 08440934337

the value of i is 10
----------------------------------------------------------------------------------------------------------------------------------

Q9. What do you mean my storage classes? How many storage classes are available in
C++?
Answer :
Storage class are used to specify the visibility/scope and life time of symbols
(functions and variables). That means, storage classes specify where all a variable or function can
be accessed and till what time those variables will be available during the execution of program.
In C++ there are 4 different storage classes available:

auto
register

static

extern

summary of c++ storage class specifiers :

C++ Storage
Specifier

Storage
Location

Scope Of
Variable

Life Time

auto

Memory
(RAM)

Local

With in function

static

Memory
(RAM)

Local

Life time is from when the flow reaches the first


declaration to the termination of program.

register

CPU register

Local

With in function

extern

Memory
(RAM)

Global

Till the end of main program

auto: Variables defined within the function body are called automatic variables. Automatic
variable, also called as local variable and it has scope only within the function block where it is
defined. auto is the keyword used to declare automatic variables. auto is the default storage
class for local variables. Local variables are variables declared within a function or blocks (after
the opening brace, { of the block). Local variables are automatic by default. They can be accessed
only from with in the declaration scope. auto variables are allocated at the beginning of enclosing
block and deallocated at the end of enclosing block.

40

Copy write by saurabh singh naruka 08440934337

Example

auto int x, y, z = 10;


is same as
int x, y, z = 10;

C++ program of auto storage class.


#include<iostream.h>
#include<conio.h>
void function(void)
{
auto int i = 1 ;
i++;
cout<<i;
}
void main()
{
function();
function();
function();
function();
getch();
}
Output:-

2222

In the above example, every time the method function() is invoked, memory is allocated for i
and de allocated at the end of the method. So it's output will be same.

41

Copy write by saurabh singh naruka 08440934337

register: It's similar to auto variables. Difference is that register variables might be stored on the
processor register instead of RAM, that means the maximum size of register variable should be
the size of CPU register ( like 16bit, 32bit or 64bit). The keyword used to declare a register
variable is register. This is normally used for frequently accessed variables like counters, to
improve performance. But note that, declaring a variable as register does not mean that they will
be stored in the register. It depends on the hardware and implementation.
Example:
{
register int i;
}

C++ program of register storage class.


#include<iostream.h>
#include<conio.h>
void main()
{
register int i;
int array[10] = {0,1,2,3,4,5,6,7,8,9};
for (i=0;i<10;i++)
{
cout<<array[i];
}
getch();
}
Output:

0123456789

static: A static variable will be kept in existence till the end of the program unlike creating and
destroying each time they move into and out of the scope. This helps to maintain their value even
if control goes out of the scope. When static is used with global variables, they will have internal
linkage that means it cannot be accessed by other source files. When static is used in case of a
class member, it will be shared by all the objects of a class instead of creating separate copies for
42

Copy write by saurabh singh naruka 08440934337

each object. static is the keyword used to declare a static variable. In C++, when static is used
on a class data member, it causes only one copy of that member to be shared by all objects of its
class.
Example:
static int i;
C++ program of static storage class.
#include<iostream.h>
#include<conio.h>
void function(void)
{
static int i = 1 ;
i++;
cout<<i;
}

void main()
{
function();
function();
function();
function();
getch();
}
Output:

2345

43

Copy write by saurabh singh naruka 08440934337

Since static variable will be kept in existence till the end of program, variable i will retain its value
across the method invocations.
extern: External variables are variables that are recognized globally, rather than locally. In other
words, extern variable is like global variable, its scope is through out the program. It can be
defined anywhere in the c++ program. A variable defined outside a function is external. An
external variable can also be declared within the function that uses it by using the keyword
extern hence it can be accessed by other code in other files. extern symbols have static storage
duration, that is accessible throughout the life of program. Since no storage is allocated for extern
variable as part of declaration, they cannot be initialized while declaring. The external storage
class is most commonly used when there are two or more files sharing the same global variables
or functions as explained below.
Example:
extern void display();
extern int count;

C++ program of extern storage class.

First File : first.cpp


#include <iostream.h>
#include <conio.h>
#include "second.cpp"
int count ;
extern void display();
void main()
{
display();
getch();

44

Copy write by saurabh singh naruka 08440934337

Second File: second.cpp


#include <iostream.h>
extern int count;
void display()
{
count = 5;
cout << Count is << count << endl;
}
Output: Count is 5

Another program of extern storage class.


#include <iostream.h>
#include <conio.h>
int x = 10;
void main( )
{
extern int y ;
cout<<"x:"<< x;
cout<<"y:"<< y;
getch();
}
int y = 20 ;

45

Copy write by saurabh singh naruka 08440934337

//Output://x: 10 y: 20
---------------------------------------------------------------------------------------------------------------------------------Q10. What is Pointer? How to use pointer in C++?
Answer: a variable which stores the address of another variable is called a pointer. In other words

we can say that A pointer is a variable whose value is the address of another variable. Pointers
are said to "point to" the variable whose address they store. Like any variable or constant, we
must declare a pointer before you can work with it. The general form of a pointer variable
declaration is:

type *var-name;

Example:
int *ip;

// pointer to an integer

To Using Pointers in C++ There are few important operations, which we will do with the pointers
very frequently.
(a) We define a pointer variable
(b) Assign the address of a variable to a pointer
(c) Finally access the value at the address available in the pointer variable. This is done by using unary
operator * that returns the value of the variable located at the address specified by its operand.

Example:

#include <iostream>
#include<conio.h>
void main ()
{

46

Copy write by saurabh singh naruka 08440934337

int x = 20;

// actual variable declaration.

int *ip;

// pointer variable

ip = &x;

// store address of variable x in pointer variable ip

cout << "Value of x variable: "<<x<< endl;


cout << "Address stored in ip variable: "<< ip << endl;
cout << "Value of *ip variable: "<< *ip << endl;

// print the address stored in ip pointer variable


// access the value at the address available in pointer

getch();
}

Output:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Unit-II
Q1. What is this pointer? And what does this pointer point to?
Answer : this pointer: C++ contains a special pointer that is called this. this is a pointer that is
automatically passed to any member function when it is called and it is a pointer to the object that
generates the call. In other word we can say that this is used to represent an object that
invokes a member function. this is a pointer that points to the object for which this function was
called.
For example, this statement,

ob.show(); // assume that ob is an object

the function show( ) is automatically passed as a pointer to ob, which is the object that invokes
the call. (or we can say that ob.show() well set the pointer this to the addres fo the object ob)

47

Copy write by saurabh singh naruka 08440934337

some other important point about this pointer:

we can use keyword "this" to refer to this instance inside a class definition.

One of the main usage of keyword this is to resolve ambiguity between the names of data
member and function parameter. For example,

only member functions are passed a this pointer. For example a friend does not have a this
pointer.

Example program of this pointer.

#include<iostream.h>
#include<string.h>
#include<conio.h>
class student
{
char name[20];
int rollno;
char section;
public:
student(char *n, int r, char s)
{
strcpy(this -> name, n);
this -> rollno = r;
this -> section = s;
}
48

Copy write by saurabh singh naruka 08440934337

void show()
{
cout << "student name: " <<

this -> name <<endl;

cout << "student rollno: " << this -> rollno <<endl;
cout << "studnet section: "<< this -> section;
}
};
void main()
{
student ob("saurabh",49,'A');
ob.show();
getch();
}

output:
student name: saurabh
student rollno: 49
studnet section: A

Here the member variables are accessed explicitly through the this pointer. Thus, within show( ),
these two statements are equivalent:
rollno = 49;
this->rollno = 49;

49

Copy write by saurabh singh naruka 08440934337

Q2.

What is Function? Also explain How to call a function with example?

Answer: Functions are building blocks of the programs. A Function is a set of statements that can
be used anywhere in the program. Function make the programs more modular and easy to read
and manage. Main reason for using it is to structure the programming by creating function for
repetitive tasks.
All C++ programs must contain the function main( ). The execution of the program starts from
the function main( ).
Each function has its own name. When that name is encountered in a program, the execution of
the program branches to the body of that function. When the function is finished, execution
returns to the area of the program code from which it was called, and the program continues on to
the next line of code.
Function is divided into three sections:

Function Declaration
Function Call
Function Definition

Function Declaration: The declaration, called the FUNCTION PROTOTYPE, informs the compiler
about the functions to be used in a program, the argument they take and the type of value they
return. A function declaration is made by declaring the return type of the function, name of the
function and the data types of the parameters of the function and Always terminated by
semicolon. The return_type specifies the type of the data the function returns. The parameter list
could be empty . The parameter list should contain both data type and name of the variable.
Function Declaration Syntax:
return-type function-name(parameter list);

Define the function:


The function definition tells the compiler what task the function will be performing. The function
prototype and the function definition must be same on the return type, the name, and the
parameters. The only difference between the function prototype and the function header is a
semicolon.
The function definition consists of the function header and its body. The header is EXACTLY like
the function prototype, EXCEPT that it contains NO terminating semicolon.

Example :
50

Copy write by saurabh singh naruka 08440934337

//Prototyping, defining and calling a function


#include <iostream.h>
void starline();

// prototype the function

int main()
{
starline( );

// function call

cout<< "saurabh naruka\n";


starline( );

// function call

return 0;
}

// function definition
void starline()
{
int count;

// declaring a LOCAL variable

for(count = 1; count <=20; count++)


cout<< "*";
cout<<endl;
}
Output : ********************
Saurabh naruka
********************

Calling Of A Function:
the function can be called using either of the following methods:

51

Copy write by saurabh singh naruka 08440934337

i) call by value
ii) call by reference

Pass by value :

Pass by value or Call by value is the method where a copy of the value of
the variables are passed to the function to do specific operation to return the result. The actual
values of the variable remains unchanged as changes are made to the copied values of the
variables.
By default, C++ uses call by value to pass arguments. In general, this means that code within a
function cannot alter the arguments used to call the function.

Program: C++ program to call the function swap() by passing actual values.

#include <iostream>
// function definition to swap the values.
void swap(int x, int y)
{
int temp;
temp = x;
x = y;

/* save the value of x */


/* put y into x */

y = temp;

/* put x into y */

return;
}

void main ()
{
int a = 100;
52

Copy write by saurabh singh naruka 08440934337

int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
}

Output:
Before swap, value of a: 100
Before swap, value of b: 200
After swap, value of a: 100
After swap, value of b: 200

Pass by reference : Pass

by reference or Call by reference is the method by which the


address of the variables are passed to the function. The "&" symbol is used to refer the address of
the variables to the function.
Program: C++ program to call the function swap() by passing values by reference.

#include <iostream>
// function definition to swap the values.
void swap(int &x, int &y)
{
int temp;
temp = x;

/* save the value at address x */


53

Copy write by saurabh singh naruka 08440934337

x = y;
y = temp;

/* put y into x */
/* put x into y */

return;
}
void main ()
{
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
}

Output:
Before swap, value of a: 100
Before swap, value of b: 200
After swap, value of a: 200
After swap, value of b: 100

Return by reference: A function can also return a reference.

Example:

54

Copy write by saurabh singh naruka 08440934337

#include<iostream.h>
#include<conio.h>
int &max(int &x,int &y)
{
if(x>y)
return x;
else
return y;
}
int main()
{
int m=1,n=2;
max(m,n)=4;
cout<<"Value of m"<<m<<endl;
cout<<"value of n"<<n<<endl;
getch();
return 0;
}

Output:
Value of m
value of n

1
4

-----------------------------------------------------------------------------Q3. What is Friend Function with example ? Also explain what is Friend Class ?

55

Copy write by saurabh singh naruka 08440934337

Friend Functions: A C++ friend functions are special functions which can access the private
members of a class. A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though the prototypes for
friend functions appear in the class definition, friends are not member functions.A friend can be a
function, function template, or member function, or a class or class template, in which case the
entire class and all of its members are friends.To declare a function as a friend of a class, precede
the function prototype in the class definition with keyword friend as follows:
#include <iostream>
#include<conio>
class Box
{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
void Box::setWidth( double wid )
{
width = wid;
}
void printWidth( Box box )
{
cout << "Width of box : " << box.width <<endl;
}
void main( )
{
Box box;
box.setWidth(10.0);
printWidth( box );
getch();
}

output: width of the box : 10


For instance: when it is not possible to implement some function, without making private
members accessible in them. This situation arises mostly in case of operator overloading.
In the following example, the friend function print is a member of class TWO and accesses the
private data members a and b of class ONE.
#include <iostream>
class ONE;
56

Copy write by saurabh singh naruka 08440934337

class TWO
{
public:
void print(ONE& x);
};
class ONE
{
int a, b;
friend void TWO::print(ONE& x);
public:
ONE() : a(1), b(2) { }
};
void TWO::print(ONE& x)
{
cout << "a is " << x.a << endl;
cout << "b is " << x.b << endl;
}
int main()
{
ONE xobj;
TWO yobj;
yobj.print(xobj);
}
Output: a is 1
b is 2
Friend functions have the following properties:

Friend of the class can be member of some other class.


Friend of one class can be friend of another class or all the classes in one program, such a
friend is known as GLOBAL FRIEND.

Friend can access the private or protected members of the class in which they are declared
to be friend, but they can use the members for a specific object.

Friends are non-members hence do not get this pointer.


Friends, can be friend of more than one class, hence they can be used for message passing
between the classes.
57

Copy write by saurabh singh naruka 08440934337

Friend can be declared anywhere (in public, protected or private section) in the class.

Friend Class: A class can also be declared to be the friend of some other class. When we create a
friend class then all the member functions of the friend class also become the friend of the other
class. This requires the condition that the friend becoming class must be first declared or defined
(forward declaration).
#include <iostream>
#include<conio.h>
class MyClass
{
// Declare a friend class
friend class SecondClass;
public:
MyClass() : Secret(0){}
void printMember()
{
cout << Secret << endl;
}
private:
int Secret;
};
class SecondClass
{
public:
void change( MyClass& yourclass, int x )
{
yourclass.Secret = x;
}
};
void main()
{
MyClass my_class;
SecondClass sec_class;
my_class.printMember();
sec_class.change( my_class, 5 );
my_class.printMember();
getch();
}
output: 0
5
58

Copy write by saurabh singh naruka 08440934337

Note:we declared friend class SecondClass; in the class MyClass, so we can access Secret in the class
SecondClass.
Another property of friendships is that they are not transitive: The friend of a friend is not considered to be a
friend unless explicitly specified.

----------------------------------------------------------------------------------------------------------Q4. What is inline function? Explain its features and limitations.


Answer: An inline function is a function that expanded in line when it is invoked. C++ inline
functions are special functions, for which the compiler replaces the function call with
body/definition of function. Inline functions are actual functions, which are copied everywhere
during compilation, like preprocessor macro, so the overhead of function calling is reduced. Inline
functions makes the program execute faster than the normal functions, since the overhead
involved in saving current state to stack on the function call is avoided. By giving developer the
control of making a function as inline, he can further optimize the code based on application logic.
But actually, it's the compiler that decides whether to make a function inline or not regardless of
it's declaration. Compiler may choose to make a non inline function inline and vice versa.
Declaring a function as inline is actually a request to the compiler to make it inline, which compiler
may ignore. So it is upto the compiler to make a function inline or not.

All the functions defined inside class definition are by default inline, but you can also make
any non-class function inline by using keyword inline with them. For an inline function,
declaration and definition must be done together.
Syntax:
inline function-header
{
Function body
}

For example,
inline void fun(int a)
{
return a++;

59

Copy write by saurabh singh naruka 08440934337

Inline Function Program:


#include<iostream.h>
#include<conio.h>
inline int min(int a, int b)
{
return (a < b)? a : b;
}
void main( )
{
cout << "min (30,10): " << min(30,10) << endl;
cout << "min (0,10): " << min(0,10) << endl;
cout << "min (100,110): " << min(100,110) << endl;
getch();
}

output:
10
0
100
If the complier decides to make the function min as inline, then the above code will internally look as if it was
written like
int main( )
{
cout << "min (20,10): " << ((20 < 10)? 20 : 10) << endl;

60

Copy write by saurabh singh naruka 08440934337

cout << "min (0,200): " << ((0 < 200)? 0 : 200) << endl;
cout << "min (100,1010): " << ((100 < 1010)? 100 : 1010) << endl;
return 0;
}
Features of Inline function:

(i) Inline functions definition is placed where it is called in the program.


(ii) It provides faster execution by ignoring the function calling process.
(iii) Member function of class is defined inline by default.
(iv)We can define any function as inline using the keyword inline while defining it.
(v) Inline functions makes the program execute faster than the normal functions, since the
overhead involved in saving current state to stack on the function call is avoided.
(vi) It avoids the overhead of calling the actual function. This is because the complier performs
and inline expansion which eliminates the time overhead when a function is called.
(vii) Reduces space as no separate set of instructions in memory is written.
(viii) It is used for functions that need fast execution.
Limitations of Inline Functions:
(I)
The compiler is unable to perform inlining if the function is too complicated. So we must
avoid big looping conditions inside such functions. In case of inline functions, entire function body
is inserted in place of each call, so if the function is large it will affect speed and memory badly.
(II)
Also, if we require address of the function in program, compiler cannot perform inlining on
such functions. Because for providing address to a function, compiler will have to allocate storage
to it. But inline functions doesn't get storage, they are kept in Symbol table.
(III) If following statements written in function body, the inline function may not work

If inline function is recursive.

Loop, switch and goto statement

Static variable

Returning from exit(0) statement


61

Copy write by saurabh singh naruka 08440934337

Some Important points about Inline Functions:


1.

Function is made inline by putting a word inline in the beginning.

2.

Inline function should be declared before main() function.

3.

It does not have function prototype.

4.
Only shorter code is used in inline function If longer code is made inline then compiler
ignores the request and it will be executed as normal function.
5.

We must keep inline functions small, small inline functions have better efficiency.

6.
Inline functions do increase efficiency, but we should not make all the functions inline.
Because if we make large functions inline, it may lead to code bloat, and might affect the speed
too.
7.
Hence, it is advised to define large functions outside the class definition using scope
resolution ::operator, because if we define such functions inside class definition, then they become
inline automatically.
8.
Inline functions are kept in the Symbol Table by the compiler, and all the call for such
functions is taken care at compile time.
----------------------------------------------------------------------------------------------------------------------------------

Q5: What is constructor? What is the use of Constructor? Explain all types of
Constructor?
Answer: Constructors: A constructor is a special member function that takes the same name as
the class name. Constructor is automatically called when object is created in other words we can
say that the constructor is automatically named when an object is created. A constructor is named
whenever an object is defined or dynamically allocated using the new operator.
Use of Constructor : The main use of constructors is to initialize objects. The function of
initialization is automatically carried out by the use of a special member function called a
constructor.
Defining Constructor and Destructor functions :
The example below illustrates how constructor and destructor functions are defined:
class myclass
{
62

Copy write by saurabh singh naruka 08440934337

private:
int number;
public:
myclass()

//constructor

{
number=10;
}
~myclass() //destructor
{

};

Some important points about constructors:

A constructor takes the same name as the class name.

constructor functions should not be preceded by any data type (not even void).

The programmer cannot declare a constructor as virtual or static, nor can the programmer
declare a constructor as const, volatile, or const volatile.

No return type is specified for a constructor.

The constructor must be defined in the public. The constructor must be a public member.

Overloading of constructors is possible.

Type of Constructors:
Default Constructor: A constructor that accepts no parameters is known as default constructor.

The default Constructor is also called as the no argument constructor. If no constructor is defined
then the compiler supplies a default constructor.
Example:
class student
{
student() { } //Default/Implicit Constructor
};
63

Copy write by saurabh singh naruka 08440934337

Another Example:
class student
{
private:
int rollno, age;
public:
student();
...
};

student :: student()
{
rollno = 0;
age = 0;
}
Parameterized Constructor : A constructor that receives arguments/parameters, is called parameterized
constructor.
Example:
student :: student(int r)
{
rollno = r;
}

Copy Constructor : A constructor that initializes an object using values of another object passed
to it as parameter, is called copy constructor. It creates the copy of the passed object. or in other
words we can say that A copy constructor is a special constructor that creates a new object from
an existing object. or Copy constructor is a special constructor of a class which is used to create
copy of an object.

64

Copy write by saurabh singh naruka 08440934337

Compiler will give a default copy constructor if we don't define one. This implicit constructor will
copy all the members of source object to target object.
Example:
student :: student(student &t)
{
rollno = t.rollno;
}
There can be multiple constructors of the same class, provided they have different signatures.
The copy constructor gets called in the following cases:

An object is passed to a method by value or returned by value.

An object is initialized using the syntax, MyClass a = b.

An object is placed in a braced-enclosed initializer list.

An object is thrown or caught in an exception.

Destructor : A destructor is a member function having same name as that of its class
preceded by ~(tilde) sign and which is used to destroy the objects that have been created by a
constructor. It gets invoked when an objects scope is over. Generally, the destructor function is
needed only when constructor has allocated dynamic memory. The main use of destructors is to
release dynamic allocated memory.
Example:
~student() { }

Some important points about destructors:

Destructor take the same name as the class name. destructor function having (~) before its
name.

Destructor functions should not be preceded by any data type (not even void).

Like the constructor, the destructor must also be defined in the public. The destructor must
be a public member.
65

Copy write by saurabh singh naruka 08440934337

The Destructor does not take any argument which means that destructors cannot be
overloaded.

No return type is specified for destructors.

Program: In this program constructors, destructor and other member functions are defined inside
class definitions. Since we are using multiple constructor in class so this example also illustrates
the concept of constructor overloading
#include<iostream.h>
#include<conio.h>
class student //specify a class
{
private :
int rollno; //class data members
float marks;
public:
student() //default constructor
{
rollno=0;
marks=0.0;
}
student(int r, int m) //parameterized constructor
{
rollno=r;
marks=m;
}
student(student &t) //copy constructor
{
66

Copy write by saurabh singh naruka 08440934337

rollno=t.rollno;
marks=t.marks;
}
void getdata() //member function to get data from user
{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}
void showdata() // member function to show data
{
cout<<"\nRoll number: "<<rollno<<"\nMarks: "<<marks;
}
~student() //destructor
{}
};

void main()
{
student st1; //defalut constructor invoked
student st2(5,78); //parmeterized constructor invoked
student st3(st2); //copy constructor invoked
st1.showdata(); //display data members of object st1
st2.showdata(); //display data members of object st2
st3.showdata(); //display data members of object st3
67

Copy write by saurabh singh naruka 08440934337

getch();

Output:
Roll number: 0
Marks: 0
Roll number: 5
Marks: 78
Roll number: 5
Marks: 78

Example 2:
#include<iostream.h>
#include<conio.h>
class student //specify a class
{
public:
student() //default constructor
{
cout<<"constructor called";
}

~student() //destructor
{}
};
68

Copy write by saurabh singh naruka 08440934337

void main()
{

student s1; //s1 id an object of class student

getch();

Q6. Explain static data member and static member function with example.
Answer: Static Members: a static member is a member that you can have access to without
instantiating the class into an object. For example, you can read and write static properties
and call static methods without ever creating the class. Static members are also called class
members (class methods, class properties, etc.) since they belong to the class and not to a
specific object. Static methods neither require an instance of the class nor can they implicitly
access the data of such an instance. A static method is distinguished in some programming
languages with the keyword static placed somewhere in the methods signature. Static
methods are called static because they are resolved statically (i.e. at compile time), in
statically typed languages, based on the class they are called on; and not dynamically, as in
the case with instance methods which are resolved polymorphically based on the runtime
type of the object. Therefore, static methods cannot be overridden.
A static member variable has certain special characteristics these are:

It is initialized to zero when the first object of its class is created. No other initialization is
permitted.
Only one copy of that member is created for the entire class and is shared by all the objects
of that class, no matter how many objects are created.
It is visible only within the class, but its lifetime is the entire program.

Static variables are normally used to maintain values common to the entire class.

69

Copy write by saurabh singh naruka 08440934337

Example program of static data member.


#include<iostream.h>
#include<conio.h>
class student
{
private:
int i;
static int s;
public:
void set_i(int a)
{
i = a;
}
static void set_s(int a)
{
s = a;
}
void show_i()
{
cout<<"value of i = "<<i<<endl;
cout<<"again, value of i = "<<this->i<<endl;
}
static void show_s()
{
cout<<"value of s = "<<s<<endl;
}

70

Copy write by saurabh singh naruka 08440934337

};

int student :: s = 786;

//Initialize static data member

void main()
{
student obj;
obj.set_i(11);
obj.show_i();

student::show_s();
student::set_s(22);
student::show_s();
getch();
}

output:
Value of i = 11
Again, value of i = 11
Value of s = 786
Value of s = 22

STATIC MEMBER FUNCITON: Static is something that holds its position. Static is a keyword which can be
used with data members as well as the member functions. A function is made static by using static keyword
with function name. These functions work for the class as whole rather than for a particular object of a class.
It can be called using the object and the direct member access operator But, its more typical to call a static
member function by itself, using class name and scope resolution :: operator.

a static member function has following properties:


71

Copy write by saurabh singh naruka 08440934337

a static function can have access to only other static members declared in the same class.
a static member function can be called using the class name as follows:

Synatax:
class_name : : function_name;

Example :
class X
{
public:
static void f(){};
};
int main()
{
X::f();
// calling member function directly with class name
}

These functions cannot access ordinary data members and member functions, but only static data members and
static member functions. It doesn't have any "this" keyword which is the reason it cannot access ordinary
members.
----------------------------------------------------------------------------------------------------------------Q7. What is overloading? Explain function overloading and operator overloading?

Answer: Overloading: The process of making a function or an operator behave in different

manners is known as overloading.


Function overloading:
Function overloading means the use of the same function name to create functions that perform a variety of
different tasks. The functions would perform different operations depending on the argument list in the
function call. The correct function to be invoked is selected by seeing the number and type of the arguments
but not the function type. For example an overloaded function volume() handles different types of data as
shown below:
int volume(int s);
double volume(double r, int h);
long volume(long l, long b,int h);

The two functions with the same name will differ at least in one of the following.
a) The number of parameters
72

Copy write by saurabh singh naruka 08440934337

b) The data type of parameters


c) The order of appearance

Example program of function overloading


#include <iostream.h>
#include<conio.h>
class arithmetic
{
public:
void calc(int num1)
{
cout<<"Square of a given number: " <<num1*num1 <<endl;
}

void calc(int num1, int num2 )


{
cout<<"Product of two whole numbers: " <<num1*num2 <<endl;
}
};

int main() //begin of main function


{
arithmetic a;
a.calc(4);
a.calc(6,7);
getch();
}

73

Copy write by saurabh singh naruka 08440934337

Output: Square of a given number: 16


Product of two whole numbers: 42

Operator overloading: Operator overloading refers to adding a special meaning to an operator. The
operator doesnt lose its original meaning but the new meaning is added for that particular class. Operator
overloading is a type of polymorphism in which an operator is overloaded to give user defined meaning to it.
Overloaded operator is used to perform operation on user-defined data type. For example '+' operator can
be overloaded to perform addition on various data types, like for Integer, String(concatenation) etc.
there are few operator which can not be overloaded. Operator that are not overloaded are follows

scope operator - ::
sizeof

member selector - .

member pointer selector - *

ternary operator - ?:

C++ allows most operators to be overloaded so that their behavior can be defined for just
about any type, including classes. Here is a list of all the operators that can be
overloaded:
Overloadable operators
+

<<= >>= ==
~

&=

delete

^=
new[]

|=

<
!=

>
<=

&&

||

+=
>=
%=

-=

*=

/=

++

--

[]

()

<<
&

->* ->

>>
!

new

delete[]

Operators are overloaded by means of operator functions, which are regular functions
with special names: their name begins by the operator keyword followed by the operator
sign that is overloaded. The syntax is:
type operator sign (parameters) { /*... body ...*/ }

74

Copy write by saurabh singh naruka 08440934337

For example, cartesian vectors are sets of two coordinates: x and y. The addition
operation of two cartesian vectors is defined as the addition both x coordinates together,
and both y coordinates together. For example, adding the cartesian vectors (3,1) and
(1,2) together would result in (3+1,1+2) = (4,3). This could be implemented in C++ with
the following code:
Example program of overloading operators.
#include <iostream>
#include<conio.h>
class CVector {
public:
int x,y;
CVector () {};
CVector (int a,int b) : x(a), y(b) {} // function name CVector (constructor)
CVector operator + (const CVector&); // function that returns a CVector
};

CVector CVector::operator+ (const CVector& param) {


CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return temp;
}

int main () {
CVector foo (3,1);
CVector bar (1,2);

75

Copy write by saurabh singh naruka 08440934337

CVector result;
result = foo + bar;
cout << result.x << ',' << result.y << '\n';
getch();
return 0;
}

Output: 4,3

When an overloaded function is called, the C++ compiler selects the proper function by examining the
number, types and order of the arguments in the call.
----------------------------------------------------------------------------------------------------------------------------

Q8. Explain difference between Function overloading and function overriding:


Function overloading : Function overloading means the use of the same function name to create functions
that perform a variety of different tasks. The functions would perform different operations depending on the
argument list in the function call. The correct function to be invoked is selected by seeing the number and type of
the arguments but not the function type. For example an overloaded function volume() handles different types of
data as shown below:

int volume(int s);


double volume(double r, int h);
long volume(long l, long b,int h);
Function overridding : Defining a function in the derived class with same name as in the parent class is
called overriding. In C++, the base class member can be overridden by the derived class function with the
same signature as the base class function. Method overriding is used to provide different implementations of
a function so that a more specific behavior can be realized

Difference between overriding and overloading:


Overriding

Overloading

Methods name and signatures must be same. Having same method name with different
76

Copy write by saurabh singh naruka 08440934337

Signatures.
Overriding is the concept of runtime
polymorphism

Overloading is the concept of compile time


polymorphism

When a function of base class is re-defined in


the derived class called as Overriding

Two functions having same name and return


type, but with different type and/or number of
arguments is called as Overloading

It needs inheritance.

It doesn't need inheritance.

Method should have same data type.

Method can have different data types

Method should be public.

Method can be different access specifies

----------------------------------------------------------------------------------------------------------------------------------Q9. How to overloading unary and binary operator? Explain with example.
Answer: There are two types of operator overloading:

Unary operator overloading


Binary operator overloading

Unary operator overloading : When we have an operator that works on single operand such type
of overloading is known as unary operator overloading. Here is the example of Unary operator
overloading:
Here is the example of binary operator overloading:
#include<iostream.h>
#include<conio.h>
class minus
{
private:
int a,b,c;
public:
void get()
{
cout<<"Enter value";
cin>>a>>b>>c;
}
77

Copy write by saurabh singh naruka 08440934337

void display()
{
cout<<"Minus";
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
void operator -()
{
a=-a;
b=-b;
c=-c;
}
};
void main()
{
minus m;
m.get();
m.display();
-m; // m.operator-();
m.display();
getch();
}
Output:
Enter value1
2
3
Minus1
2
3
Minus-1
-2
-3
Binary operator overloading: When we have an operator that works on two operands such type of
overloading is known as binary operator overloading.

#include<iostream.h>
#include<conio.h>
class sum
{
private:
int x,y;
78

Copy write by saurabh singh naruka 08440934337

public:
sum()
{
x=10;
y=10;
}
void display()
{
cout<<"\nvalue of x is "<<x;
cout<<"\nvalue of y is "<<y;
}
sum operator +(sum obj)
{
sum t;
t.x=obj.x+x;
t.y=obj.y+y;
return t;
}
};
void main()
{
sum s1,s2,s3;
s1=s2+s3; // s1=s2.operator +(s3);
s1.display();
79

Copy write by saurabh singh naruka 08440934337

s2.display();
s3.display();
getch();
}

Output:
value of x is 20
value of y is 20
value of x is 10
value of y is 10
value of x is 10
value of y is 10
-----------------------------------------------------------------------------------------------------Q10. Define Rules for operator overloading.
Answer: The rules for operator overloading are as follows:
New operators are not created. Only the current operators are overloaded.
The overloaded operator must have at least one operand of user defined type.
We cannot change the basic meaning of the operator.
When binary operators are overloaded through a member function then the left hand operand is
implicitly passed as and thus it must be an object.
When binary operators are overloaded through a member function then it take one explicit
argument And when binary operators are overloaded through a friend function take two explicit
arguments.
When Unary operators are overloaded through member functions will not take any explicit argument
and not return any explicit values. But when operators are overloaded through member functions will
take one explicit argument.
Binary arithemetic operators (+,-,*,/) must explicitly return a value.
80

Copy write by saurabh singh naruka 08440934337

some operator given below cant be overloaded.


Sizeof
.

Size of operator
Membership operator

.*

Pointer to member operator

::

Scope resolution operator

?:

Conditional operator

some operator like (= , () , [] , ->) cant be overloaded through friend functions.

Restrictions on Operator Overloading


Following are some restrictions to be kept in mind while implementing operator overloading.
1. Precedence and Associativity of an operator cannot be changed.
2. Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary remains binary etc.
3. No new operators can be created, only existing operators can be overloaded.
4. Cannot redefine the meaning of a procedure. You cannot change how integers are added.
----------------------------------------------------------------------------------------------------------------------------------

Unit - 3
Q1. What is inheritance? What are the advantages of inheritance?

Answer: Inheritance allows one class to inherit properties of another class. In other words,
Inheritance is the process of forming a new class from an existing class that is from the existing
class called as base class, new class is formed called as derived class. The ":" operator is used for
inheriting a class.

81

Copy write by saurabh singh naruka 08440934337

The advantage of using "Inheritance" is due to the reusability of classes in multiple derived
classes.It helps to modularise the code, improve reusability and reduces tight coupling between
components of the system. Inheritance helps in reducing the overall code size of the program .
The following table lists the visibility of the base class members in the derived classes.

Derived class visibility


Base class visibility
Public derivation.

Private derivation.

Protected derivation.

Private

Not inherited

Not inherited

Not inherited

Protected

Protected

Private

Protected

Public

Public

Private

Protected

class Shape
{
public:
int getSize()
{
return size;
}
void setSize(int w)
{
size = w;
}
protected:
int size;
};

// Derived class

82

Copy write by saurabh singh naruka 08440934337

class Square: public Shape


{
public:
int getArea()
{
return (size * size);
}
};

In the above example, class Square inherits the properties and methods of class Shape.

Following are the different types of inheritance followed in C++.

Single inheritance
Multiple inheritance

Multilevel inheritance

Hierarchical inheritance

Hybrid inheritance

83

Copy write by saurabh singh naruka 08440934337

Single Inheritance : Single Inheritance is method in which a derived class has only one base class.
Most Easy Example:
//single level inheritance
#include<iostream.h>
#include<conio.h>
class A
{
public:
void show1()
{
cout<<"u are in parent class A\n";
}
};
class B : public A
84

Copy write by saurabh singh naruka 08440934337

{
public:
void show2()
{
cout<<"u are in parent class B";
}
};
void main()
{
B b;
clrscr();
b.show1();
b.show2();
getch();
}

Output:
u are in parent class A
u are in parent class B

-----------------------------Multiple Inheritance : Multiple Inheritance is a method by which a class is derived from more than one base
class.
Most easy example:
//multiple level inheritance

85

Copy write by saurabh singh naruka 08440934337

#include<iostream.h>
#include<conio.h>
class A
{
public:
void show1()
{
cout<<"u are in parent class A\n";
}
};
class B
{
public:
void show2()
{
cout<<"u are in parent class B\n";
}
};
class C : public A , public B
{
public:
void show3()
{
cout<<"u are in parent class C";
86

Copy write by saurabh singh naruka 08440934337

}
};
void main()
{
C c;
clrscr();
c.show1();
c.show2();
c.show3();
getch();
}

Output:
u are in parent class A
u are in parent class B
u are in parent class C
--------------------------------Multilevel Inheritance : Multilevel Inheritance is a method where a derived class is derived from another derived
class.
Most easy Example:
//multi level inheritance
#include<iostream.h>
#include<conio.h>
class A

87

Copy write by saurabh singh naruka 08440934337

{
public:
void show1()
{
cout<<"u are in parent class A\n";
}
};
class B : public A
{
public:
void show2()
{
cout<<"u are in parent class B\n";
}
};
class C : public B
{
public:
void show3()
{
cout<<"u are in parent class C";
}
};
void main()
88

Copy write by saurabh singh naruka 08440934337

{
C c;
clrscr();
c.show1();
c.show2();
c.show3();
getch();
}

Output:
u are in parent class A
u are in parent class B
u are in parent class C

Hierarchical Inheritance : Hierarchical Inheritance is a method of inheritance where one or more derived
classes is derived from common base class.
Most easy Example:
//Hierarchical Inheritance
#include<iostream.h>
#include<conio.h>
class A
{
public:
void show1()
{

89

Copy write by saurabh singh naruka 08440934337

cout<<"u are in parent class A\n";


}
};
class B : public A
{
public:
void show2()
{
cout<<"u are in parent class B\n";
}
};
class C : public A
{
public:
void show3()
{
cout<<"u are in parent class C";
}
};
void main()
{
B b;
C c;
clrscr();
90

Copy write by saurabh singh naruka 08440934337

cout<<"methods run using class B object\n";


b.show1();
b.show2();
cout<<"methods run using class C object\n";
c.show1();
c.show3();
getch();
}

Output:
methods run using class B object
u are in parent class A
u are in parent class B
methods run using class C object
u are in parent class A
u are in parent class C
Hybrid Inheritance : Hybrid Inheritance is a method where one or more types of inheritance are combined
together and used.
Example:

//Hybridge Inheritance
#include<iostream.h>
#include<conio.h>
class A
{
91

Copy write by saurabh singh naruka 08440934337

public:
void show1()
{
cout<<"u are in parent class A\n";
}
};
class B : public A
{
public:
void show2()
{
cout<<"u are in parent class B\n";
}
};

class D
{
public:
void show4()
{
cout<<"u are in parent class D\n";
}
};
92

Copy write by saurabh singh naruka 08440934337

class C : public B,public D


{
public:
void show3()
{
cout<<"u are in parent class C\n";
}
};

void main()
{
C c;
clrscr();
c.show1();
c.show2();
c.show3();
c.show4();
getch();
}

Output:
u are in parent class A
u are in parent class B
93

Copy write by saurabh singh naruka 08440934337

u are in parent class C


u are in parent class D
--------------------------------------------------------------------------------------------------------------------------------------------------Q2. What is polymorphism. Explain both compile time and run time polymorphism with
example.
Ans: Polymorphism is the property of representing one operation into many different forms. One operation
may express differently in different situations. The process of making a function or an operator behave in
different manners is known as overloading the function or the operator. Polymorphism is one of the most
useful features of object oriented programming. It can be achieved both at run time and at compile
time.

compile time polymorphism : At compile time polymorphism is achieved using function


overloading and operator overloading. At the time of compilation the compiler knows about
the exact matching as to which function to call or invoke. This is known as compile time
polymorphism or early binding.
The following example program explains how polymorphism can be accomplished using function
overloading.

#include <iostream.h>
#include<conio.h>
class arithmetic
{
public:
void calc(int num1)
{
cout<<"Square of a given number: " <<num1*num1 <<endl;
}

void calc(int num1, int num2 )

94

Copy write by saurabh singh naruka 08440934337

{
cout<<"Product of two whole numbers: " <<num1*num2 <<endl;
}
};

int main() //begin of main function


{
arithmetic a;
a.calc(4);
a.calc(6,7);
getch();
}

Output: Square of a given number: 16


Product of two whole numbers: 42

Run time Polymorphism : Polymorphism can also be achieved at run time. This is done using
the concept of virtual functions. Which class function is to be invoked is decided at run time and
then the corresponding object of that class is created accordingly. This is also called as late
binding.
For this concept we always need to make use of pointers to objects.
The example illustrates the concept of virtual functions:

#include<iostream.h>
#include<conio.h>
class base

95

Copy write by saurabh singh naruka 08440934337

{
public:
int i;
base(int x)
{
i=x;
}

virtual void func()


{
cout<<"\n using base version of function";
cout<<i<<endl;
}
};

class derived: public base


{
public:
derived(int x):base(x){}
void func()
{
cout<<"\n using derived version";
cout<<i*i<<endl;
}
};

96

Copy write by saurabh singh naruka 08440934337

class derived1: public base


{
public:
derived1(int x): base(x){}
void func()
{
cout<<"\n using derived1 version";
cout<<(i+i)<<endl;
}
};

void main()
{
base *p;
base ob(10);
derived d_ob(10);
derived1 d_ob1(10);
p=&ob;
p->func();
p=&d_ob;
p->func();
p=&d_ob1;
p->func();
getch();
}

97

Copy write by saurabh singh naruka 08440934337

Output:
using base version of function 10

using derived version 100

using derived1 version 20

----------------------------------------------------------------------------------------------------Q3. Explain the rule of using virtual function?


Answer

The virtual functions must be member of some class.


They are accessed by using object pointers.

A virtual function can be a friend of another class.

A virtual function in a base class must be defined. even though it may not be used.

The prototypes of the base class version of a virtual function and all the derived
class versions must be identical. If two functions with the same name have
different prototypes, C++ considers them as overloaded functions. and the virtual
function mechanism is ignored.

We cannot have virtual constructors, but we can have virtual destructors.

While a base pointer can point to any type of the derived object, the reverse is not
true. that is to say, we cannot use a pointer to a derived class to access an object
of the base type.

When a base pointer points to a derived class, incrementing or decrementing it


will not make it to point to the next object of the derived class. It is incremnted or
decremented only relative to its base type. Therefore, we should not use this
method to move the pointer to the next object.

If a virtual function is defined in the abse class, it need not be necessarily


redefined in the derived class. In such cases, calls will invoke the base function.

-----------------------------------------------------------------------------------------------------------------------------------Q4. What are virtual functions and what is its use?


98

Copy write by saurabh singh naruka 08440934337

virtual functions are used to implement run time polymorphism in c++ .Virtual functions are
member functions of class which is declared using keyword 'virtual'. When a base class type
reference is initialized using object of sub class type and an overridden method which is declared
as virtual is invoked using the base reference, the method in child class object will get invoked.

//virtual function
#include<iostream.h>
#include<conio.h>
class base
{
public:
void display()
{
cout<<"\n display base ";
}
virtual void show()
{
cout<<"\n virtual show base \n";
}
};

class derived : public base


{
public:
void display()
{
cout<<" \n display derived ";
}
99

Copy write by saurabh singh naruka 08440934337

void show()
{
cout<<" \n show derived";
}
};

void main()
{
base B;
derived D;
base *bptr;
cout<<"bprt point to base";
bptr = &B;
bptr -> display();

// call base class function

bptr -> show();

// call base class funtion

cout<<"\nbprt point to derived ";


bptr = &D;
bptr -> display();

// call base class function

bptr -> show();

// call derived class function

getch();
}

output:
bprt point to base

100

Copy write by saurabh singh naruka 08440934337

display base
virtual show base
bprt point to derived
display base
show derived
In the above example even though the method in invoked on Base class reference, method of the child will get
invoked since its declared as virtual.
---------------------------------------------------------------------------------------------------------------------------Q5. What is a pure virtual function? Why pure virtual functions are used if they don't
have implementation? When does a pure virtual function become useful?
Answer: pure virtual function has no definition related to the base class. A pure virtual function is
a function that has the notation "= 0" in the declaration of that function. Only the function
prototype is included to make a pure virtual function the following syntax is used:
Syntax:
virtual return_type function_name(par_list) = 0;
Example of a pure virtual function in C++
class SomeClass {
public:
virtual void pure_virtual() = 0; // a pure virtual function
};
there is no function body
Pure Virtual function: A pure virtual function has no definition related to the base class. Only
the function prototype is included to make a pure virtual function the following syntax is used:
Syntax:
virtual return_type function_name(par_list) = 0;
Example:
101

Copy write by saurabh singh naruka 08440934337

virtual void show()=0;


Example program of Pure virtual function.
#include<iostream.h>
#include<conio.h>
class base
{
public:
virtual void show()=0;
};

class child1: public base


{
public:
void show()
{
cout<<"child1"<<endl;
}
};

class child2: public base


{
public:
void show()
{
102

Copy write by saurabh singh naruka 08440934337

cout<<"child2";
}
};

void main()
{
base *b;
child1 c1;
child2 c2;

b=&c1;
b->show();
b=&c2;
b->show();
getch();
}

Output: child1
child2
The pure specifier: The "= 0" portion of a pure virtual function is also known as the pure
specifier, because its what makes a pure virtual function pure. Although the pure specifier
appended to the end of the virtual function definition may look like the function is being assigned
a value of 0, that is not true. The notation "= 0" is just there to indicate that the virtual function
is a pure virtual function, and that the function has no body or definition.
Use of Pure virtual function: In C++, a regular, "non-pure" virtual function provides a
definition, which means that the class in which that virtual function is defined does not need to be
103

Copy write by saurabh singh naruka 08440934337

declared abstract. You would want to create a pure virtual function when it doesnt make sense to
provide a definition for a virtual function in the base class itself, within the context of inheritance.

---------------------------------------------------------------------------------------------------------------------------Q6. What is the difference between a virtual function and a pure virtual function? Give example of
each.
Ans: Virtual functions are important because they support polymorphism at run time. A virtual
function is a member function that is declared within the base class but redefined inside the
derived class. To create a virtual function we precede the function declaration with the keyword
virtual. Thus we can assume the model of one interface multiple method. The virtual function
within the base class defines the form of interface to that function. It happens when a virtual
function is called through a pointer.
Example Program of virtual function:
#include<iostream.h>
#include<conio.h>
class base
{
public:
void display()
{
cout<<"\n display base ";
}
virtual void show()
{
cout<<"\n virtual show base \n";
}

104

Copy write by saurabh singh naruka 08440934337

};

class derived : public base


{
public:
void display()
{
cout<<" \n display derived ";
}
void show()
{
cout<<" \n show derived";
}
};

void main()
{
base B;
derived D;
base *bptr;
cout<<"bprt point to base";
bptr = &B;
bptr -> display();

// call base class function

bptr -> show();

// call base class function


105

Copy write by saurabh singh naruka 08440934337

cout<<"\nbprt point to derived ";


bptr = &D;
bptr -> display(); // call base class function
bptr -> show();

// call derived class function

getch();
}

output:
bprt point to base
display base
virtual show base

bprt point to derived


display base
show derived

Pure Virtual function: A pure virtual function has no definition related to the base class. Only
the function prototype is included to make a pure virtual function the following syntax is used:
Syntax:
virtual return_type function_name(par_list) = 0;
Example:
virtual void show()=0;

106

Copy write by saurabh singh naruka 08440934337

Example program of Pure virtual function.


#include<iostream.h>
#include<conio.h>
class base
{
public:
virtual void show()=0;
};

class child1: public base


{
public:
void show()
{
cout<<"child1"<<endl;
}
};

class child2: public base


{
public:
void show()
{
cout<<"child2";
107

Copy write by saurabh singh naruka 08440934337

}
};

void main()
{
base *b;
child1 c1;
child2 c2;

b=&c1;
b->show();
b=&c2;
b->show();
getch();
}

Output: child1
child2
------------------------------------------------------------------------------------------------------Q7. What is abstract class? Explain with example.
Answer: A class that contains at least one pure virtual function is considered an abstract class. An abstract
class is something which is to be hidden by people and on which modifications can be done in future. Since
an abstract class contains at least one function for which no body exists, technically it can be considered as
incomplete and therefore no object is created. Thus we can also define an abstract class as a class for which
no object is created. We may conclude that an abstract class exists only to be inherited. We may still create
pointer to an abstract class.
108

Copy write by saurabh singh naruka 08440934337

Example: class area is an abstract class because it has a pure virtual function.

class area
{
public:
virtual void get_area()=0;
};
we cannot create an object of an abstract class type; however, you can use pointers and references to
abstract class types.

----------------------------------------------------------------------------------------------------------------------------

Q8. What is virtual destructor? Why they are used?


Virtual destructors are used for the same purpose as virtual functions. When you remove an
object of subclass, which is referenced by a parent class pointer, only destructor of base class will
get executed. But if the destructor is defined using virtual keyword, both the destructors [ of
parent and sub class ] will get invoked.
In order to define a virtual destructor, all you have to do is simply add the keyword virtual
before the tilde symbol.
the need for virtual destructors in C++ is explain by following two examples.
Example without a Virtual Destructor:
#include <iostream.h>
class Base
{
public:
Base(){ cout<<"Constructing Base";}
// this is a destructor:
~Base(){ cout<<"Destroying Base";}
};

109

Copy write by saurabh singh naruka 08440934337

class Derive: public Base


{
public:
Derive(){ cout<<"Constructing Derive";}
~Derive(){ cout<<"Destroying Derive";}
};

void main()
{
Base *basePtr = new Derive();
delete basePtr;
}

Output:
Constructing Base
Constructing Derive
Destroying Base

In this program the constructors get called in the appropriate order when we create the Derive class object pointer
in the main function. But there is a major problem with the code above: the destructor for the "Derive" class does
not get called at all when we delete basePtr.
So, to fix this problem we can make the base class destructor virtual, and that will ensure that the destructor for
any class that derives from Base (in our case, its the "Derive" class) will be called.
Example with a Virtual Destructor:
#include <iostream.h>
#include<conio.h>
class Base
{
110

Copy write by saurabh singh naruka 08440934337

public:
Base(){ cout<<"Constructing Base";}
// this is a destructor:
virtual ~Base(){ cout<<"Destroying Base";}
};

class Derive: public Base


{
public:
Derive(){ cout<<"Constructing Derive";}
~Derive(){ cout<<"Destroying Derive";}
};

void main()
{
Base *basePtr = new Derive();
delete basePtr;
getch();
}

Output:
Constructing Base
Constructing Derive
Destroying Derive
Destroying Base

[Note: the derived class destructor will be called before the base class.]
111

Copy write by saurabh singh naruka 08440934337

---------------------------------------------------------------------------------------------------------------------------------------Q9. What is Virtual base class? Give example and also explain its uses.
Answer: When two or more objects are derived from a common base class, we can prevent multiple
copies of the base class being present in an object derived from those objects by declaring the base
class as virtual when it is being inherited. Such a base class is known as virtual base class. This can
be achieved by preceding the base class name with the word virtual.
Example program of virtual base class.
#include<iostream.h>
#include<conio.h>
class A
{
public:
int i;
};

class B : virtual public A


{
public:
int j;
};

class C: virtual public A


{
112

Copy write by saurabh singh naruka 08440934337

public:
int k;
};

class D: public B, public C


{
public:
int sum;
};

void main()
{
D ob;
ob.i = 10; //unambiguous since only one copy of i is inherited.
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout << "Value of i is : "<< ob.i<<"\n";
cout << "Value of j is : "<< ob.j<<"\n";
cout << "Value of k is :"<< ob.k<<"\n";
cout << "Sum is : "<< ob.sum <<"\n";

113

Copy write by saurabh singh naruka 08440934337

getch();
}

output:
Value of i is : 10
Value of j is : 20
Value of k is :30
Sum is : 60
------------------------------------------------------------------------------------------------------------

Q10. The keyword virtual can be used for functions as well as classes in C++. Explain the two
different uses. Give an example each.
Ans: Virtual function: virtual functions are important because they support polymorphism at
run time. A virtual function is a member function that is declared within the base class but
redefined inside the derived class. To create a virtual function we precede the function
declaration with the keyword virtual. Thus we can assume the model of one interface multiple
method. The virtual function within the base class defines the form of interface to that
function. It happens when a virtual function is called through a pointer. The following example
illustrates the use of a virtual function:
#include<iostream.h>
#include<conio.h>
class base
{
114

Copy write by saurabh singh naruka 08440934337

public:
int i;
base(int x)
{
i=x;
}
virtual void func()
{
cout<<"\n using base version of function ";
cout<<i<<endl;
}
};
class derived: public base
{
public:
derived(int x):base(x){}
void func()
{
cout<<"\n using derived version ";
cout<<i*i<<endl;
}
};
class derived1: public base
{
public:
derived1(int x): base(x){}
void func()
{
cout<<"\n using derived1 version ";
cout<<(i+i)<<endl;
}
};
void main()
{
base *p;
base ob(10);
derived d_ob(10);
derived1 d_ob1(10);
p=&ob;
p->func();
p=&d_ob;
115

Copy write by saurabh singh naruka 08440934337

p->func();
p=&d_ob1;
p->func();
getch();
}
Output:
using base version of function 10
using derived version 100
using derived1 version 20
Virtual class: The concept of virtual class is very important as far as inheritance is
concerned. Basically, the need for a making a class virtual arises when all the three basic types
of inheritance exist in the same program- Multiple, multilevel and hierarchical inheritance.
For instance suppose we create a class child which inherit the properties of two other classes
parent1 and parent2 and these two parent classes are inherited from a grandparent class. The
grandfather class is the indirect base class for child class. Now the class child will have
properties of the grandfather class but inherited twice, once through both the parents. The child
can also inherit the properties straight from its indirect base class grandfather. To avoid the
ambiguity caused due to the duplicate sets of inherited data we declare the common base class
as virtual. Those classes that directly inherit the virtual class will be declared as follows:
class grandparents
{
....
....
};
116

Copy write by saurabh singh naruka 08440934337

class parent1: virtual public grandparents


{
....
....
};
class parent2: public virtual grandparents
{
....
....
};
class child: public parent1,public parent2
{
....//only one copy of grandparents
....//will be inherited.
};
------------------------------------------------------------------------------------------------------------

Unit - 4
Q.1 What is meant by exceptions? How an exception is handled in C++? Explain with the help of an
example.
Ans: Exception Handling: Using exception handling we can more easily manage and respond to run time
errors. C++ exception handling is built upon 3 keywords: try, catch and throw.
The try block contains program statements that we want to monitor for exceptions.
The throw block throws an exception to the catch block if it occurs within the try block.
117

Copy write by saurabh singh naruka 08440934337

The catch blocks proceeds on the exception thrown by the throw block.
When an exception is thrown, it is caught by its corresponding catch statement which processes the
exception. There can be more that one catch statement associated with a try. The catch statement that is
used is determined by the type of the exception. An example below illustrates the working of the three
blocks.
#include <iostream.h>
int main()
{
int x,y;
cout << "Enter values of x::";
cin >> x;
cout << "Enter values of y::";
cin >> y;

int r=x/y;
try
{
if ( r!=0)
{
cout << "Result of division is x/r:: " << x/r << "\n";
}
else
{
throw ( r);
}
}
catch( int r)
{
cout << "Division by zero exception:: value of r is::" << r << "\n";

118

Copy write by saurabh singh naruka 08440934337

}
cout << "END";
return 0;
}
Result:

Enter values of x::12


Enter values of y::12
Division by zero exception::value of r is::0
---------------------------------------------------------------------------------------

Q2(a). When do we used multiple catch handlers?


(b). When do you rethrow any (caught) exception? Give the syntax.
Answer(a): Just like we use conditions in a switch statement, we can use multi catch statements with one
try block when a program has to throw an exception based on more than one condition. The multi handlers
are searched in sequence of which they occur. The first match that is found is executed. If no match is found
then the program terminates.
A program may have more than one condition to throw an exception. For this we can use more than one
catch block in a program. An example is shown below illustrate the concept:
#include<iostream.h>
using namespace std;
void test(int x){
try {
if(x==1) throw x;
else
if(x==0) throw 'x';
else
if(x==-1) throw 1.0;
cout<<"End of try-block\n";
}
119

Copy write by saurabh singh naruka 08440934337

catch(char c) {
cout<<"Caught a character \n";
}
catch(int m) {
cout<<"Caught an integer\n";
}
catch(double d) {
cout<<"Caught a double\n";
}
cout<<""End of try-catch system\n\n;}
int main(){
cout<<"Testing multiple catches\n";
cout<<"x==1\n";
test(1);
cout<<"x==0\n";
test(0);
cout<<"x==-1\n";
test(-1);
cout<<"x==2\n";
test(2); return 0;}
Output:

Testing Multiple Catches


x==1
Caught an integer
End of try-catch system
x==0
120

Copy write by saurabh singh naruka 08440934337

Caught a character
End of try-catch system
x==-1
Caught a double
End of try-catch system
x==2
End of try-block
End of try-catch system
Answer(b) Ans: An exception handler can rethrow an exception that it has caught without even processing it.

It simply invokes the throw without passing any arguments.


throw;
This exception is then thrown to the next try/catch and is caught by a catch statement listed after that
enclosing try block.

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------Q3. What is an exception specification? When is it used?


Answer: Exception specifications are used to provide summary information about what exceptions can be
thrown out of a function. Exceptions not listed in an exception specification should not be thrown from that function.

An exception specification consists of the keyword throw after the function's parameter list, followed by a
list of potential exceptions, for example:

void test(int somecode) throw (bad_code, no_auth);

An exception specification isn't considered a part of a function's type. Therefore, it doesn't affect overload
resolution. That means pointers to functions and pointers to member functions may contain an exception
specification, for example:
void (*PtrFunct)(double) throw(string, double);

PtrFunct is a pointer to a function that may throw string or double. we can assign to a function whose
exception specification is as restrictive as, or more restrictive than PtrFunct 's exception specification.
An exception specification P is said to be more restrictive than an exception specification Q if the set of
exceptions P contains is a subset of Q's exceptions. In other words, P contains every exception in Q but not
vice versa. For example:
121

Copy write by saurabh singh naruka 08440934337

void (*PtrFunct)(double) throw(string, double);

//more restrictive than PtrFunct:


void One(double) throw (string);
//as restrictive as PtrFunct:
void Two(double) throw (string, double);
//less restrictive than PtrFunct:
void Three(double) throw (string, double, bool);
PtrFunct = One; //OK
PtrFunct = Two; //OK
PtrFunct = Three; //error, Three is not subset of the PtrFunct

A function with no exception-specification allows all exceptions. A function with an empty exception
specification doesn't allow any exceptions, for example:
class Test
{
public:
//may throw any exception
int One(char *VarPtr);
//doesn't throw any exception
int Two(double *VarPtr1) throw();
};

Exception specifications are enforced at the runtime. When a function violates its exception specification,
unexpected() function is called. The unexpected() function invokes a user-defined function that was
previously registered by calling set_unexpected(). If no function was registered with set_unexpected(),
unexpected() calls terminate() which aborts the program unconditionally. The following table summarizes
C++'s implementation of exception specifications:

122

Copy write by saurabh singh naruka 08440934337

Exception specification table


Exception specification

Meaning

throw()

The function does not throw any exception.

throw(...)

The function can throw an exception.

throw(type)

The function can throw an exception of type type.

The following are examples of the exception specification implementation.


Example

Description

void Funct() throw(int)

The function may throw an int exception.

void Funct() throw()

The function will throw no exceptions.

void Funct() throw(char*, T)

The function may throw a char* and/or a T, user defined type


exception.

void Funct() or

The function

void Funct(...)

If exception handling is used in an application, there must be one or more functions that handle thrown
exceptions.
123

Copy write by saurabh singh naruka 08440934337

Any functions called between the one that throws an exception and the one that handles the exception must
be capable of throwing the exception. However, explicit exception specifications are not allowed on C
functions.
//exception specification

#include <iostream>
#include<conio.h>

124

Copy write by saurabh singh naruka 08440934337

using namespace std;


//handler function
void handler()
{cout<<"In the handler()\n";}
//int throw...
void Funct1(void) throw(int)
{
static int x = 1;
cout<<"Funct1() call #"<<x++<<endl;
cout<<"About to throw 1\n";
if (1)
throw 1;
}
//empty throw...
void Funct5(void) throw()
{
try
{Funct1();}
catch(...)
{handler();}
}
// invalid, doesn't handle the int exception thrown from Funct1()
// void Funct3(void) throw()
// {

125

Copy write by saurabh singh naruka 08440934337

// Funct1();
//}
void Funct2(void)
{
try
{Funct1();
} catch(int)
{handler();}
}
//assume extern "C" functions don't throw exceptions
extern "C" void Funct4(void);
void Funct4(void)
{Funct1();}
int main()
{
Funct2();
try
{Funct4();}
catch(...)
{cout<<"Caught exception from Funct4()\n";}
Funct5();
getch();
return 0;
}

126

Copy write by saurabh singh naruka 08440934337

output:
Funct1() call #1
About to throw 1
In the handler()
Funct1() call #2
About to throw 1
Caught exception from Funct4()
Funct1() call #3
About to throw 1
In the handler():
-------------------------------------------------------------------------------------Q4. What are generic classes? Why are they useful? Explain with an example how these are implemented in
c++.
Answer: Templates allow us to define generic classes. A generic class is a class that can be used with any
data type. When we declare a generic class we are able to define all algorithms used by that class but the
actual type data being manipulated will be specified as a parameter when object of that class is created.
Generic classes are useful when a class contains generalised logic. For example the algorithm that is used to
maintain a queue of integer can also be used for a queue of character. The compiler will automatically
generate the correct type of object based upon the type you specify when the object is created. General
form generic class:
template <class type> class class-name
{
//body;
}
Here the type is place holder type-name that will be specified when the object of the class is created. We can
define more than one generic data-type by using comma separated list. To create an object
Class-name <data type> object-name;

127

Copy write by saurabh singh naruka 08440934337

Member functions of a generic class are themselves automatically generic. They need not be explicitly
specified by using template.

--------------------------------------------------------------------------------------------------------Q5. What is Templates? Explain its type with example.


Answer: Templates are the foundation of generic programming which involves writing code in a
way that is independent of any particular type. Templates are also known as generic functions or
classes which are used to implement a generic structure for many structures of the same
statements with different data-types. So we can say that A template is a blueprint or formula for
creating a generic class or a function. The library containers like iterators and algorithms are
examples of generic programming and have been developed using template concept.
You can use templates to define functions as well as classes. We can declare a template with the
keyword template. Like so:
template<typename T>
template<class T>

The template keyword tells the compiler that what follows is a template, and that T is a template
parameter that identifies a type.
Note: The name T is often used, but we could give it any name we want.
There are two types of templates:

Function templates
Class templates

Function Template: Function templates are special functions that can operate with generic
types. This allows us to create a function template whose functionality can be adapted to more
than one type or class without repeating the entire code for each type. In C++ this can be
achieved using template parameters. A template parameter is a special kind of parameter that
can be used to pass a type as argument: just like regular function parameters can be used to
pass values to a function, template parameters allow to pass also types to a function. These
function templates can use these parameters as if they were any other regular type.
Function templates are declared in the following way:
template <class identifier> function_declaration;

128

Copy write by saurabh singh naruka 08440934337

or
template <typename identifier> function_declaration;

The only difference between both prototypes is the use of either the keyword class or the keyword
typename.we can use the keyword class or the keyword typename. Its use is indistinct, since both
expressions have exactly the same meaning and behave exactly the same way.
For example, to create a template function that returns the greater one of two objects we could
use:

template <class myType>


myType GetMax (myType a, myType b) {
return (a>b?a:b);
}
To use this function template we use the following format for the function call:
function_name <type> (parameters);
For example, to call GetMax to compare two integer values of type int we can write:

int x,y;
GetMax <int> (x,y);
Here is the entire example:

// function template
#include <iostream>
using namespace std;
template <class T>
T GetMax (T a, T b) {
T result;
result = (a>b)? a : b;
return (result);
}
int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax<int>(i,j);
n=GetMax<long>(l,m);
cout << k << endl;
129

Copy write by saurabh singh naruka 08440934337

cout << n << endl;


return 0;
}
Output: 6
10

Function templates have the following advantages:

Function overloading can be easily implemented.


A function is expanded by the compiler when needed, so unnecessary burden of computer
power during execution, is reduced.

Codes written are in generic mode, so any changes made will be reflected in each definition
automatically.

Class Template: Class templates are associated with the generic types and they can use some
specific types as well. But all objects must be of some specific size, so before creating an object of
the template class, the data-type must be specified. This is done by specifying the data-type as
parameter when the object is created for the template class. Template classes are a great help for
creating applications with generic types, which are common applications such as linked list, stack,
and queues etc. Just as we can define function templates, we can also define class templates.
Class templates are declared in the following way:
template <class identifier> class_declaration;
or
template <typename identifier> class_declaration;

we can use the keyword class or the keyword typename. Its use is indistinct, since both
expressions have exactly the same meaning and behave exactly the same way.
simple stack example:
#include <iostream>
#include<conio.h>
#include <string>
using namespace std;

template <class T>


130

Copy write by saurabh singh naruka 08440934337

class Stack
{
public:
Stack();
void push(T i);
T pop();
private:
int top;
T st[100];
};

template <class T>


Stack<T>::Stack()
{
top = -1;
}

template <class T>


void Stack<T>::push(T i)
{
st[++top] = i;
}

template <class T>


T Stack<T>::pop()
{
return st[top--];
}

131

Copy write by saurabh singh naruka 08440934337

int main ()
{
Stack<int> int_stack;
Stack<string> str_stack;
int_stack.push(10);
str_stack.push("Hello");
str_stack.push("World");
cout << int_stack.pop() << endl;
cout << str_stack.pop() << endl;
cout << str_stack.pop() << endl;
getch();
return 0;
}
Ouput:
10
World
Hello

advantages of class templates

One C++ Class Template can handle different types of parameters.


Compiler generates classes for only the used types. If the template is instantiated for int
type, compiler generates only an int version for the c++ template class.

Templates reduce the effort on coding for different data types to a single set of code.

Testing and debugging efforts are reduced.

---------------------------------------------------------------------------------------------------------------------------------------------------------Q.6 How are template functions overloaded? Explain with a suitable example.
Ans: A template function can be overloaded using a template functions. It can also be overloaded using
ordinary functions of its name. The matching of the overloaded function is done in the following manner.
132

Copy write by saurabh singh naruka 08440934337

a. The ordinary function that has an exact match is called.


b. A template function that could be created with an exact match is called.
c. The normal matching process for overloaded ordinary functions is followed and the one that
matches is called. If no match is found, an error message is generated. Automatic conversion facility is not
available for the arguments on the template functions.
The following example illustrates an overloaded template function:
#include <cstdlib>
#include <iostream>
#include<conio.h>
#include<string.h>

using namespace std;


template<class T>
void display(T x)
{
cout<<"all data types"<<x<<"\n";
}
void display(float x)
{
cout<<"integer data type "<<x<<"\n";
}
int main()
{
display(20);
display(3.6);
display('A');
getch();
return 0;

133

Copy write by saurabh singh naruka 08440934337

output:
all data types20
all data types3.6
all data typesA
-------------------------------------------------------------------------------------Q7. What is the difference between Function template and inline function?
Function templates are those functions which can handle different data types without separate code for
each of them. For a similar operation on several kinds of data types, a programmer need not write different
versions by overloading a function. It is enough if he writes a C++ template based function. This will take
care of all the data types. An example that finds the maximum value of an array using template is given
below:
#include<iostream.h>
template<class T>
void max(T a[],T &m,int n)
{
for(int i=0;i<n;i++)
if(a[i]>m)
m=a[i];
}
int main()
{
int x[5]={10,50,30,40,20};
int m=x[0];
max(x,m,5);
cout<<"\n The maximum value is : "<<m;
return 0;

134

Copy write by saurabh singh naruka 08440934337

}
Output:
The maximum value is : 50
Inline Functions: An inline function is one for which the compiler copies the code from the function
definition directly into the code of the calling function rather than creating a separate set of instructions in
memory. Instead of transferring control to and from the function code segment, a copy of the function body
may be substituted directly for the function call. In this way, the performance overhead of a function call is
avoided. A function is declared inline by using the inline function specifier or by defining a member function
within a class or structure definition. The inline specifier is only a suggestion to the compiler that an inline
expansion can be performed; the compiler is free to ignore the suggestion.
The following code fragment shows an inline function definition.
inline int add(int i, int j) { return i + j;}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------Q8. (a) When is a template a better solution than a base class?
(b) What is difference between template and macro?
Answer(a): When you are designing a generic class to contain or otherwise manage objects of other types,
when the format and behavior of those other types are unimportant to their containment or management,
and particularly when those other types are unknown (thus, the genericity) to the designer of the container
or manager class.
Answer (b): In C++ there is a major difference between a template and a macro. A macro is merely a string
that the compiler replaces with the value that was defined.
E.g. #define STRING_TO_BE_REPLACED "ValueToReplaceWith"
A template is a way to make functions independent of data-types. This cannot be accomplished using
macros. E.g. a sorting function doesn't have to care whether it's sorting integers or letters since the same
algorithm might apply anyway.
---------------------------------------------------------------------------------------------------------------------------------------------------------Q9. Write a template function that swaps the values of two arguments passed to it. In main( ), use the
function with integers and characters.
Ans:
#include<iostream.h>

135

Copy write by saurabh singh naruka 08440934337

#include<conio.h>
template <class T>
void swap(T &a ,T &b)
{
T temp = a;
a = b;
b = temp;
}
void func(int x , int y , char w , char z)
{
cout<<"x and y before swap: "<<x<<y<<"\n";
swap(x,y);
cout<<"x and y after swap: "<<x<<y<<"\n";
cout<<"w and z before swap: "<<w<<z<<"\n";
swap(w,z);
cout<<"w and z after swap: "<<w<<z<<"\n";
}
int main()
{
func(10,20,'s','S');
getch();
return 0;
}

Output:
x and y before swap: 10 20
136

Copy write by saurabh singh naruka 08440934337

x and y after swap: 20 10


w and z before swap: s S
w and z after swap: S s

---------------------------------------------------------------------------Q.10 Write a template function to find the maximum number from a template array of size N.
Ans:
#include<iostream.h>
#include<conio.h>
template<class T>
void max(T a[],T &m, int n)
{
for(int i=0;i<n;i++)
if(a[i]>m)
m=a[i];
}
int main()
{
int x[5]={10,50,30,40,20};
int m=x[0];
max(x,m,5);
cout<<"\n The maximum value is : "<<m;
getch();
return 0;
}

Output:
The maximum value is : 50

137

Copy write by saurabh singh naruka 08440934337

----------------------------------------------------------------------------Unit - 5
Q.1 What are the two methods of opening a file? Explain with examples. What is the difference
between the two methods?
Ans: For opening a file, we first create a file stream which we can link to the file name. we can define a file
stream using 3 classes namely ifstream, ofstream and fstream that are all contained in the header file
fstream. Which class to use shall depend upon the mode in which we want to open the file that is read or
write. There are 2 modes to open a file.
Using the constructor function of the class
Using the member function open() of the class.
When using the first method that is constructor function of the class, we initialize the file stream object by
file name. for example the following statement opens a file named results for input.
ifstream infile (results);
When using the second method of function open(), multiple files can be opened that use the same stream
object for example when we wish to process a number of files in sequential manner, we shall create a single
stream object and use it to open each file in turn. The syntax is as follows:
file-stream-class stream-object;
stream-object.open(filename);
The basic difference between the two methods is that the constructor function of the class is used when
we wish to open just one file in the stream. The open function is used when we wish to open multiple
files using one stream.

------------------------------------------------------------------------------------------------------------Q.2 Describe the different modes in which files can be opened in C++.
Ans: Different modes in which files can be opened in C++.

138

Copy write by saurabh singh naruka 08440934337

---------------------------------------------------------------------------------------------------------------------------------------------------------------Q.3 Explain the following functions(with example) for manipulating file pointers:
seekg(),seekp(),tellg(),tellp().
Ans: A file pointer is used to navigate through a file. We can control this movement of the file
pointer by ourselves. The file stream class supports the following functions to manage such
situations.
seekg ():moves get pointer (input) to a specified location.
seekp ():moves put pointer (output) to a specified location.
tellg ():gives the current position of the get pointer.
139

Copy write by saurabh singh naruka 08440934337

tellp (): gives the current position of the put pointer.


For example:
infile.seekg (10); will move the file pointer to the byte number 10.
ofstream fileout;
fileout.open(morning, ios::app);
int p = fileout.tellp();
the above statements will move the output pointer to the end of the file morning and the value
of p will represent the number of bytes in the file.
seekg and seekp can also be used with two arguments as follows.
seekg (offset, ref position);
seekp (offset, ref position);
where offset referes to the number of bytes the file pointer is to be moved from the location
specified by the parameter ref position.

The following program demonstrates the use of the seekp() and


the tellp() functions.
// Program
#include<iostream.h>
#include<fstream.h>
void main()
{
long pos;
ofstream outfile;
outfile.open (test.txt);
outfile.write (This is an apple,16);
pos=outfile.tellp();
outfile.seekp (pos-7);
outfile.write ( sam,4);
outfile.close();
}
Output: This is a sample

140

Copy write by saurabh singh naruka 08440934337

---------------------------------------------------------------------------------------------------------------------------------------------------------------Q4. write a class to represent a vector (a series of float values). Include member functions to perform the
following tasks:
1)To Create the Vector
2)To modify the value of a given element
3)To multiply by a scalar value.
4)To display the vector in the form (10,20,30....)
Answer:
#include <iostream.h>
#include <conio.h>

intconst size=50;

class vector
{
float d[size];
int s;
public:
void create(void);
void modify(void);
void multiply(void);
void display(void);
};

void vector :: create(void)


{
141

Copy write by saurabh singh naruka 08440934337

cout<<"\n\nEnter of Array you want to create:-";


cin>>s;
cout<<"Enter "<<s<<" Real Numbers\n";
for(int i=0;i<s;i++)
cin>>d[i];
}

void vector :: modify(void)


{
int mfy_value;
float with;
cout<<"\nEnter Location of array at which value is to be modified:-";
cin>>mfy_value;
cout<<"Enter Value with which you want to Replace:-";
cin>>with;
d[mfy_value]=with;
}

void vector :: multiply(void)


{
int mul;
cout<<"\nEnter value with which you want to multiply:-";
cin>>mul;
for(int i=0;i<s;i++)
d[i]=d[i]*mul;
}
142

Copy write by saurabh singh naruka 08440934337

void vector :: display(void)


{
cout<<"\n\nDisplay of Array\n";
cout<<"(";
for(int i=0;i<s;i++)
{
cout<<d[i];
if(i!=s-1)
cout<<",";
}
cout<<")";
}

void main()
{
clrscr();
vector o1;
int choice;
do
{
cout<<"\n\nChoice List\n";
cout<<"1)

To Create Vector Array\n";

cout<<"2)

To Modify Array\n";

cout<<"3)

To Multiply with Scalar value\n";

cout<<"4)

To Display\n";
143

Copy write by saurabh singh naruka 08440934337

cout<<"5)

EXIT\n";

cout<<"Enter your choice:-";


cin>>choice;
switch(choice)
{
case 1:

o1.create();

break;
case 2:

o1.modify();

break;
case 3: o1.multiply();
break;
case 4: o1.display();
break;
case 5:goto end;
}
}while(1);
end:
}

------------------------------------------------------------------------------------------------------------Q5(a) Write short note on Stream.


(b) What is generic algorithms? Explain with example.
Answer(a) Stream is defined as an interface supplied by the I/O system to the programmer and that which
is independent of the actual device being used. Stream is actually a sequence of bytes. These are basically
of two types: one is when it is a source through which input can be taken and the other is when it acts as a
destination to which output can be sent. The source stream is called the input stream and the destination
stream is called the output stream. There are several streams likewise cin is an input stream which extracts
input from the keyboard and cout is the output stream which inserts the ouput to the screen. The three
streams used are:-

144

Copy write by saurabh singh naruka 08440934337

istream(input stream).this stream inherits the properties of ios and declares input functions such get(),
getline() and read().the extraction operator used for this >>
ostream(output stream). This also inherits properties from ios and declared output functions such as put()
and write(). It uses the insertion operator <<.
Iostream(input/output stream). This inherits properties from ios istream and ostream and through multiple
inheritance contains all the input output functions.
Answer(b) The generic algorithms are a collection of routines that can be used to perform common
operations on container classes, such as sorting, merging and finding. The are called generic because they
are independent of the container class used and of the datatype of the objects held in those container
classes

------------------------------------------------------------------------------------------------------------Q6. What is the Standard Template Library (STL)? Explain with example.
Answer: The Standard Template Library, or STL, is a collection of container classes, generic algorithms
and related components that can greatly simplify many programming tasks in C++. Or in other word we can
say that The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provides
general-purpose templatized classes and functions that implement many popular and commonly used
algorithms and data structures like vectors, lists, queues, and stacks.
There are three main components to the STL: container classes, iterators and generic algorithms.
Component

Description

Containers

Containers are used to manage collections of objects of a certain kind. There are several
different types of containers like deque, list, vector, map etc.

Algorithms

Algorithms act on containers. They provide the set of fucntions by which you will perform
initialization, sorting, searching, and transforming of the contents of containers.

Iterators

Iterators provide the connection between the containers and the algorithms. Iterators are
used to step through the elements of collections of objects. These collections may be
containers or subsets of containers.

Example: following program demonstrates the vector container (a C++ Standard Template) which is
similar to an array with an exception that it automatically handles its own storage requirements in case it
grows:
#include <iostream>

145

Copy write by saurabh singh naruka 08440934337

#include <vector>
using namespace std;
int main()
{
// create a vector to store int
vector<int> vec;
int i;
// display the original size of vec
cout << "vector size = " << vec.size() << endl;
// push 5 values into the vector
for(i = 0; i < 5; i++){
vec.push_back(i);
}
// display extended size of vec
cout << "extended vector size = " << vec.size() << endl;
// access 5 values from the vector
for(i = 0; i < 5; i++){
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}

146

Copy write by saurabh singh naruka 08440934337

return 0;
}

Output:
vector size = 0
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
value of v = 4

Here are following points to be noted related to various functions we used in the above example:

The push_back( ) member function inserts value at the end of the vector, expanding its size as
needed.

The size( ) function displays the size of the vector.

The function begin( ) returns an iterator to the start of the vector.

The function end( ) returns an iterator to the end of the vector.

------------------------------------------------------------------------------------------------------------Q7(a): What is an Iterator class? Explain different types of iterators.

147

Copy write by saurabh singh naruka 08440934337

(b): What is the difference between an external iterator and an internal iterator? Describe
an advantage of an external iterator.

Anser(a): Iterators are an abstraction of pointers. Iterator class is a class that is used to traverse
containers and access objects within containers. In other word we can say that An iterator behave like
pointers and are used to access container elements. Iterators hide the details of access to and update of the
elements of a container class. Something like a pointer.
The iterators are used to link a container with an algorithm. A container class has methods to return
iterators that provide access to its contents. These iterators are provided, as arguments, to an algorithm.
The algorithm can then traverse, access and manipulate the contents of the container.
A container class hold group of objects and iterator class is used to traverse through the objects maintained
by a container class. The iterator class provides access to the classes inside a container. They are objects
that point to other objects. Iterator points to one element in a range, and then it is possible to increment it
so that it points to the next element.

There are Five categories of iterators:


Iterator Type

Description

Input Iterator

These iterators can read values in the forward movement. They can be incremented,
compared and dereferenced

Ouptut Iterator

They write values in the forward movement. They can be incremented and dereferenced

Forward Iterator

They are like input and output iterators that can read and write values in forward
movement

Bidirectional iterators

These can Read and write values with forward and backward movement and can be
incremented, decremented. Bidirectional iterators are able to iterate in two directions,
forward and backward, by using the increment operator (e.g. ++) and decrement
operators (e.g. --)respectively. The iterators of the container classes list, set, multiset,
map, and multimap are bidirectional iterators.

random_access_iterator

Can read and write values randomly. Random access iterators have all the properties of
bidirectional iterators plus they can perform random access. You can add and subtract
offsets, process differences, and compare iterators by using relational operators such as <
and >. The iterators of the container classes vector and deque, and iterators of strings are
random access iterators.
148

Copy write by saurabh singh naruka 08440934337

Answer(b): An internal iterator is implemented with member functions of the class that has items to step
through. An external iterator is implemented as a separate class that can be "attach" to the object that has
items to step through. .An external iterator has the advantage that many difference iterators can be active
simultaneously on the same object.

------------------------------------------------------------------------------------------------------------Q8. What is a container class? Explain its types in C++.


Answer: A class is said to be a container class which is utilized for the purpose of holding objects in
memory or persistent media or we can say that container class is a class that used to hold objects of any
particular type. A generic class plays a role of generic holder. A container class is a good blend of predefined
behavior and an interface that is well known. The purpose of container class is to hide the topology
for the purpose of objects list maintenance in memory. It can be heterogeneous and homogeneous.
(a) Heterogeneous container : A container class is known as heterogeneous container, when it contains a set
of different objects.
(b) Homogeneous container : A container class is known as homogeneous container when it contains a set
of similar objects.
The following are the standardized container classes:

std::map

Used for handle sparse array or a sparse matrix

std::vector

Like an array, this standard container class offers additional features such as bunds checking through the at () member
function, inserting or removing elements, automatic memory management and throwing exceptions.

std::string

A better supplement for arrays of chars.

149

Copy write by saurabh singh naruka 08440934337

A map in C++ defines a mapping between any 2 types of items - a key and a value. In maps, the keys are
unique. C++ offers multimaps which can have duplicate keys. Here's a little example of using map.
Maps are ways of setting up a mapping between 2 sets of values. The map is the STLs generic
symbol table, and it allows you to specify the data type for both the key and the value. Like other
containers, map has size, begin and end member functions. The code is quite readable once you've
set up the mapping.
// map
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main ()
{
// the next line creates a mapping from strings to strings
map<string,string> car;
car["Smith"]="Ford";
car["Jones"]="Jaguar";
cout << "Smith's car is a " << car["Smith"] << endl;
cout << "Jones' car is a " << car["Jones"] << endl;
}
Output:
Smith's car is a Ford
Jones' car is a Jaguar

150

Copy write by saurabh singh naruka 08440934337

The vector: The vector is a type-safe, sequential container class that behaves like an array. You can set
the size of the vector up front, you can use operator[] to access and modify individual entries, and
you can splice new elements in anywhere you want and let the vector do all of the shifting for you.
The primary win of the vector over the array comes from its ability to grow and shrink automatically
in response to insertion and deletion. Because arrays are useful data structures all by themselves,
and because vectors are designed to not only behave like arrays but to interact with the programmer
using the same syntax, vectors are used more often than any other STL class.
Programs making use of the vector first need to #include some boilerplate at the top of any file making use
of it:
//vector
#include <vector>
using namespace std;
The most commonly used vector operations are summarized in the abbreviated class
definition presented here:
template <class T>
class vector {
public:
vector();
vector(const vector<T>& originalMap);
typedef implementation_specific_class_1 iterator;
typedef implementation_specific_class_2 const_iterator;
bool empty() const; // true iff logical length is 0
long size() const; // returns logical length of vector
void clear(); // empties the vector, sets size to 0
void push_back(const T& elem);
void pop_back();
T& operator[](int i);
151

Copy write by saurabh singh naruka 08440934337

const T& operator[](int i) const;


iterator insert(iterator where, const T& elem);
iterator erase(iterator where);
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
};

--------------------------------------------------------------------------------------------------------------------------Q9. When should we use container classes instead of arrays?


Answer: Containers is a ways of clumping together variables of the same type so that sorting, searching,
etc., becomes easy. the most commonly used container in programming is the array. array container classes
generally provide dynamically resizing (when elements are added or removed) and do bounds-checking.
This not only makes array container classes more convenient than normal arrays, but safer too. The
available containers include vector (which is a straight replacement for arrays), list, set, queue etc.
few benefits that the container classes offer over arrays.

Container classes handle all sizing and memory allocation issues. we can't write past the end of a
container class like you can with an array

Container classes are optimized for their intended use. Some allow constant time insertions at their
end, some allow this anywhere. Some are better to maintain sorted lists, some better for random access
retrievals.

They contain utility methods such as empty(), size() and clear() that can simplify programming.

They contain other methods that all insertion, deletion and copying.

They have equality, inequality and assignment operators. You can directly compare two containers or
assign on to another.

They provide iterators. Iterators are an abstraction of pointers. They allow similar syntax and use, but
also have some built-in methods and checks that increase their utility.
-----------------------------------------------------------------------------------------------------------------------152

Copy write by saurabh singh naruka 08440934337

Q10. Explain sequence container, associative container and derived container?

Answer: Sequence containers :

Sequence containers hold elements of a single type as a linear


sequence. That is, they are ordered in the same way as they are added to the container. arrays,
which are a built-in part of the language and the string class, which is part of the standard library,
may be used as sequence containers. With the sequence containers, the same data, that is, the
same sequence could be stored in any of the containers. The issue in choosing a particular container
was performance based on how the data would be manipulated, updated and accessed. Questions
such as where in the sequence insertions and deletions would be made drove the choice of container.

The STL provides three sequence containers: vector, deque and list.
Associative containers : Associative containers are designed to support direct access to element using
keys. With the associative containers, the choice of container is driven by the nature of the data to
be stored and manipulated, rather than performance. Some of the containers store key-value pairs,
some just values. Some allow duplicates, some dont.
The associative containers are specialized to allow the fastest possible retrieval (or look up) of values. This
retrieval is either by the values themselves or by a key, where each value has its own key.
There are four types of associative containers:

Set - No keys are used. Duplicates are not allowed.

Multiset - No keys are used. Duplicates are allowed.

Map - Key-value pairs are stored. Duplicates are not allowed.

Multimap - Key-value pairs are stored. Duplicates are allowed.

These standard associative containers are also known as sorted associative containers. They store their data
internally in binary tree structures.
Derived Containers : Derived container also known as container adaptors. StL provides three derived
containers: stack, queue and priority_queue. Stack queues and priority queues can be created
from different sequence containers. Derived containers do not support iterators. There for we cannot
use them for data manipulation. But they support push() and pop() member functions so they can be
use for insertion and deletion operation.
14. List down the advantages of class templates

One C++ Class Template can handle different types of parameters.


Compiler generates classes for only the used types. If the template is instantiated for int type,
compiler generates only an int version for the c++ template class.

Templates reduce the effort on coding for different data types to a single set of code.
153

Copy write by saurabh singh naruka 08440934337

Testing and debugging efforts are reduced.

17. Explain typecasting.


It is the process of converting one type into another. In other words converting an expression of a given type into
another is called type casting. Typecasting is making a variable of one type, such as an int, act like another
type, a char, for one single operation. To typecast something, simply put the type of variable you want the
actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a
char.

There are two ways of achieving the type conversion namely:


(I) Implicit Conversion (Automatic Conversion)
(II) Explicit Conversion
Implicit Conversion : This is not done by any conversions or operators. In other words the value gets automatically
converted to the specific type to which it is assigned.
Let us see this with an example:
#include <iostream>
using namespace std;
void main()
{
short x=6000;
int y;
y=x;
}

In the above example the data type short namely variable x is converted to int and is assigned to the integer
variable y.
Explicit Conversion:
Explicit conversion can be done using type cast operator and the general syntax for doing this is :
datatype (expression);

154

Copy write by saurabh singh naruka 08440934337

In C++ the type casting can be done in either of the two ways mentioned below namely:

C style casting

C++ style casting

The C style casting takes the syntax as :


(type) expression
This can also be used in C++.
The C++ style casting takes the syntax as :
type (expression)
Example: explicit type casting
#include <iostream>
#include <conio.h>
void main()
{
int a;
float b,c;
cout << "Enter the value of a:";
cin >> a;
cout << "Enter the value of b:";
cin >> b;
c = float(a)+b;
cout << "The value of c is:" << c;
getch();
}
Output:
Enter the value of a:10
Enter the value of b:12.2
The value of c is:22.2
Or there is an another example:
#include <iostream>
#include<conio.h>
void main()
{
int a;
double b=2.55;
a = b;
cout << a << endl;
155

Copy write by saurabh singh naruka 08440934337

a = (int)b;
cout << a << endl;
a = int(b);
cout << a << endl;
getch();
}
Output:
2
2
2

17b. What is the Difference between type conversion and type casting ?
Answer: Difference between type conversion and type casting
Type conversion: The Type Conversion is that which automatically converts the one data type into another
Type casting : When a user can convert the one data type into then it is called as the type casting

18. Whats the difference between public, private and protected?

private section of a class can only be

A member (either data member or member function) declared in a


accessed by member functions and friends of that class

A member (either data member or member function) declared in a protected section of a class can only be
accessed by member functions and friends of that class, and by member functions and friends of derived classes

A member (either data member or member function) declared in a


by anyone

156

public section of a class can be accessed

Copy write by saurabh singh naruka 08440934337

15. Write a short notes on recursion with example.


Recursion is defined as a function calling itself. It is in some ways similar to a loop because it
repeats the same code, but it requires passing in the looping variable and being more
careful. Many programming languages allow it because it can simplify some tasks, and it is
often more elegant than a loop.
void recurse()
{
recurse();
}
void main()
{
recurse();
}

---------------------------------------------

WHAT IS DEFAULT ARGUMENT?


A default parameter is a function parameter that has a default value provided to it. If the
user does notsupply a value for this parameter, the default value will be used. If the user does supply a
value for the default parameter, the user-supplied value is used.
ANS:

Example:
#include <iostream.h>
#include <conio.h>

void PrintValues(int nValue1, int nValue2=10)


{

cout << "1st value: " << nValue1 << endl;


cout << "2nd value: " << nValue2 << endl;

157

Copy write by saurabh singh naruka 08440934337

void main()
{
PrintValues(1); // nValue2 will use default parameter of 10
PrintValues(3, 4); // override default value for nValue2

getch();
}

Output:
1st value: 1
2nd value: 10
1st value: 3
2nd value: 4

In the first function call, the caller did not supply an argument for nValue2, so the function used the default
value of 10. In the second call, the caller did supply a value for nValue2, so the user-supplied value was
used.

158

Copy write by saurabh singh naruka 08440934337

Built-In Data Types


The basic (fundamental) data types provided by c++ are integral, floating point and void data type.
Among these data types, the integral and floating-point data types can be preceded by several
type modifiers. These modifiers (also known as type qualifiers) are the keywords that alter either size or
range or both of the data types. The various modifiers are short, long, signed and unsigned. By default
the modifier is signed.
In addition to these basic data types, ANSI C++ has introduced two more data types namely, bool and
wchar_t.
Integral Data Type: The integral data type is used to store integers and includes char (character) and
int (integer) data types.
Char: Characters refer to the alphabet, numbers and other characters (such as {, @, #, etc.) defined in
the ASCII character set. In C++, the char data type is also treated as an integer data type as the
characters are internally stored as integers that range in value from -128 to 127. The char data type
occupies 1 byte of memory (that is, it holds only one character at a time).
The modifiers that can precede char are signed and unsigned. The various character data types with
their size and range are listed in Table

159

Copy write by saurabh singh naruka 08440934337

Int: Numbers without the fractional part represent integer data. In C++, the int data type is used to
store integers such as 4, 42, 5233, -32, -745. Thus, it cannot store numbers such as 4.28, -62.533. The
various integer data types with their size and range are listed in Table

Floating-point Data Type: A floating-point data type is used to store real numbers such as 3 .28, 64.
755765, 8.01, -24.53. This data type includes float and double' data types. The various floating -point
data types with their size and range are listed in Table

Void: The void data type is used for specifying an empty parameter list to a function and return type
for a function. When void is used to specify an empty parameter list, it indicates that a function does
not take any arguments and when it is used as a return type for a function, it indicates that a function
does not return any value. For void, no memory is allocated and hence, it cannot store anything. As a
160

Copy write by saurabh singh naruka 08440934337

result, void cannot be used to declare simple variables, however, it can be used to declare generic
pointers.
Bool and wcha_t : The boo1data type can hold only Boolean values, that is; either true or false, where
true represents 1 and false represents O. It requires only one bit of storage, however, it is stored as an
integer in the memory. Thus, it is also considered as an integral data type. The bool data type is most
commonly used for expressing the results of logical operations performed on the data. It is also used as
a return type of a function indicating the success or the failure of the function.
In addition to char data type, C++ provides another data type wchar_t which is used to store 16- bit
wide characters. Wide characters are used to hold large character sets associated with some nonEnglish languages.
Derived Data Types: Data types that are derived from the built-in data types are known as derived
data types. The various derived data types provided by C++ are arrays, junctions,
references and pointers.
Array An array is a set of elements of the same data type that are referred to by the same name. All the
elements in an array are stored at contiguous (one after another) memory locations and each element is
accessed by a unique index or subscript value. The subscript value indicates the position of an element
in an array.
Function A function is a self-contained program segment that carries out a specific well-defined task.
In C++, every program contains one or more functions which can be invoked from other parts of a
program, if required.
Reference A reference is an alternative name for a variable. That is, a reference is an alias for a
variable in a program. A variable and its reference can be used interchangeably in a program as both
refer to the same memory location. Hence, changes made to any of them (say, a variable) are reflected
in the other (on a reference).
Pointer A pointer is a variable that can store the memory address of another variable. Pointers allow
to use the memory dynamically. That is, with the help of pointers, memory can be allocated or deallocated to the variables at run-time, thus, making a program more efficient.
User-Defined Data Types
Various user-defined data types provided by C++ are structures, unions, enumerations and classes.

161

Copy write by saurabh singh naruka 08440934337

Structure, Union and Class: Structure and union are the significant features of C language.
Structure and union provide a way to group similar or dissimilar data types referred to by a single
name. However, C++ has extended the concept of structure and union by incorporating some new
features in these data types to support object -oriented programming.
C++ offers a new user-defined data type known as class, which forms the basis of object-oriented
programming. A class acts as a template which defines the data and functions that are included in an
object of a class. Classes are declared using the keyword class. Once a class has been declared, its object
can be easily created.
Enumeration: An enumeration is a set of named integer constants that specify all the permissible
values that can be assigned to enumeration variables. These set of permissible values are known as
enumerators. For example, consider this statement.
enum country {US, UN, India, China};

// declaring an
// enum type

In this statement, an enumeration data-type country (country is a tag name) , consisting of


enumerators US, UN and so on, is declared. Note that these enumerators represent integer values, so
any arithmetic operation can be performed on them.
By default, the first enumerator in the enumeration data type is assigned the value zero. The value of
subsequent enumerators is one greater than the value of previous enumerator. Hence, the value of US is
0, value of UN is 1 and so on. However, these default integer values can be overridden by assigning
values explicitly to the enumerators
as shown here.
enum country {US, UN=3, India, china} ;
In this declaration, the value of US is O by default, the value of UN is 3, India is 4 and soon.
Once an enum type is declared, its variables can be declared using this statement.
country countryl, country2;
These variables countryl, country2 can be assigned any of the values specified in enum declaration only.
For example, consider these statements.
countryl India; // valid
country2 Japan; // invalid

162

Copy write by saurabh singh naruka 08440934337

Though the enumerations are treated as integers internally in C++, the compiler issues a warning, if an
int value is assigned to an enum type. For example, consider these statements.
Country1 = 3;

//warning

Country1 = UN;

/ /valid

Country1 = (country) 3; / /valid


C++ also allows creating special type of enums known as anonymous enums, that is, enums without
using tag name as shown in this statement.
enum {US, UN=3, India, China};
The enumerators of an anonymous enum can be used directly in the program as shown here.
int count = US;
The typedef Keyword
C++ provides a typedef feature that allows to define new data type names for existing data types that
may be built-in, derived or user-defined data types. Once the new name has been defined, variables can
be declared using this new name. For example, consider this declaration.
typedef int integer;
In this declaration, a new name integer is given to the data type into This new name now can be used to
declare integer variables as shown here.
integer i, j, k;
Note that the typedef is used in a program to contribute to the development of a clearer program.
Moreover, it also helps in making machine-dependent programs more portable.

163

Das könnte Ihnen auch gefallen