C++ Complete Notes
C++ Complete Notes
C++ Complete Notes
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++
structures
C Doesnt supports reference
variables
Bird birdobject;
}
};
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
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
Hybrid inheritance
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.
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
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.
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
objects.
as a real world.
specifier.
Expansion
Data Access
function.
the data
change in data.
Data Hiding
Overloading
security.
Examples
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
Q4. What are the main characteristics of an object oriented programming ? Compare Them
with the structured programming?
Answer:
Characteristics of OOPs:
i.
ii.
b.
New data types like long long int, Boolean and complex data type to denote complex
numbers.
c.
d.
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:
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
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
int a[3][4] = {
{0, 1, 2, 3} ,
{4, 5, 6, 7} ,
};
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};
14
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]
#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
--------------------------------------------------------------------------------------------------------------------
16
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 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
return x;
}
Output:
Sum of the array elements is: 16
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
Array of Objects
(ii)
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
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
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
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
getch();
}
Output:
Value of a[0] = 10
Value of a[1] = 20
Value of a[2] = 30
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
{
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
if else example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
if-else-if example:
25
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
{
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
.
.
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
break;
default:
cout<<"wrong choice";
break;
}
getch();
}
29
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
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
#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
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.
Example:
33
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
output:
1 2 3 4 5 6 7 8 9 10
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
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
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
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
}
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
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
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
C++ Storage
Specifier
Storage
Location
Scope Of
Variable
Life Time
auto
Memory
(RAM)
Local
With in function
static
Memory
(RAM)
Local
register
CPU register
Local
With in function
extern
Memory
(RAM)
Global
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
Example
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
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;
}
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
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
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;
44
45
//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
int x = 20;
int *ip;
// pointer variable
ip = &x;
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,
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
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.
#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
void show()
{
cout << "student name: " <<
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
Q2.
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);
Example :
50
int main()
{
starline( );
// function call
// function call
return 0;
}
// function definition
void starline()
{
int count;
Calling Of A Function:
the function can be called using either of the following methods:
51
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;
y = temp;
/* put x into y */
return;
}
void main ()
{
int a = 100;
52
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
#include <iostream>
// function definition to swap the values.
void swap(int &x, int &y)
{
int temp;
temp = x;
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
Example:
54
#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
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();
}
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 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.
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
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.
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
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
cout << "min (0,200): " << ((0 < 200)? 0 : 200) << endl;
cout << "min (100,1010): " << ((100 < 1010)? 100 : 1010) << endl;
return 0;
}
Features of Inline function:
Static variable
2.
3.
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
private:
int number;
public:
myclass()
//constructor
{
number=10;
}
~myclass() //destructor
{
};
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.
The constructor must be defined in the public. The constructor must be a public member.
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
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
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:
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() { }
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
The Destructor does not take any argument which means that destructors cannot be
overloaded.
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
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
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
void main()
{
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
70
};
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 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?
The two functions with the same name will differ at least in one of the following.
a) The number of parameters
72
73
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 - .
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
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
};
int main () {
CVector foo (3,1);
CVector bar (1,2);
75
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.
----------------------------------------------------------------------------------------------------------------------------
Overloading
Methods name and signatures must be same. Having same method name with different
76
Signatures.
Overriding is the concept of runtime
polymorphism
It needs inheritance.
----------------------------------------------------------------------------------------------------------------------------------Q9. How to overloading unary and binary operator? Explain with example.
Answer: There are two types of 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
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
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
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
Size of operator
Membership operator
.*
::
?:
Conditional operator
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
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.
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
In the above example, class Square inherits the properties and methods of class Shape.
Single inheritance
Multiple inheritance
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
83
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
{
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
#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
}
};
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
{
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
{
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
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
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
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
#include <iostream.h>
#include<conio.h>
class arithmetic
{
public:
void calc(int num1)
{
cout<<"Square of a given number: " <<num1*num1 <<endl;
}
94
{
cout<<"Product of two whole numbers: " <<num1*num2 <<endl;
}
};
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
{
public:
int i;
base(int x)
{
i=x;
}
96
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
Output:
using base version of function 10
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.
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.
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";
}
};
void show()
{
cout<<" \n show derived";
}
};
void main()
{
base B;
derived D;
base *bptr;
cout<<"bprt point to base";
bptr = &B;
bptr -> display();
getch();
}
output:
bprt point to base
100
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
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
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
};
void main()
{
base B;
derived D;
base *bptr;
cout<<"bprt point to base";
bptr = &B;
bptr -> display();
getch();
}
output:
bprt point to base
display base
virtual show base
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
}
};
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
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.
----------------------------------------------------------------------------------------------------------------------------
109
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
public:
Base(){ cout<<"Constructing Base";}
// this is a destructor:
virtual ~Base(){ cout<<"Destroying Base";}
};
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
---------------------------------------------------------------------------------------------------------------------------------------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;
};
public:
int k;
};
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
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
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
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
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
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
}
cout << "END";
return 0;
}
Result:
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:
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.
An exception specification consists of the keyword throw after the function's parameter list, followed by a
list of potential exceptions, for example:
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
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
Meaning
throw()
throw(...)
throw(type)
Description
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
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
125
// 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
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
Member functions of a generic class are themselves automatically generic. They need not be explicitly
specified by using template.
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
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:
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
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;
class Stack
{
public:
Stack();
void push(T i);
T pop();
private:
int top;
T st[100];
};
131
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
Templates reduce the effort on coding for different data types to a single set of code.
---------------------------------------------------------------------------------------------------------------------------------------------------------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
133
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
}
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
#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
---------------------------------------------------------------------------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
----------------------------------------------------------------------------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
---------------------------------------------------------------------------------------------------------------------------------------------------------------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
140
---------------------------------------------------------------------------------------------------------------------------------------------------------------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 main()
{
clrscr();
vector o1;
int choice;
do
{
cout<<"\n\nChoice List\n";
cout<<"1)
cout<<"2)
To Modify Array\n";
cout<<"3)
cout<<"4)
To Display\n";
143
cout<<"5)
EXIT\n";
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:
}
144
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
#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
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.
147
(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.
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
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.
std::map
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
149
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
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
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
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:
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
Templates reduce the effort on coding for different data types to a single set of code.
153
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
In C++ the type casting can be done in either of the two ways mentioned below namely:
C style casting
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
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
156
---------------------------------------------
Example:
#include <iostream.h>
#include <conio.h>
157
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
159
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
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
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
162
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
163