0% found this document useful (0 votes)
17 views57 pages

C++ Notes

Uploaded by

Arvind K
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
17 views57 pages

C++ Notes

Uploaded by

Arvind K
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 57

What is C++:

 C++ is a powerful general-purpose programming language. It can be used to develop


operating systems, browsers, games, and so on.
 C++ supports different ways of programming like procedural, object-oriented,
functional, and so on. This makes C++ powerful as well as flexible.
 C++ is an object-oriented programming language that gives a clear structure to
programs and allows code to be reused and modular structures.
 C++ is a compiled language, which means that source code is transformed into
machine code by a compiler before it can be run on a computer.
 With C++, you can develop desktop and mobile applications, heavy games that can
run on different platforms.
 C++ was developed by “Bjarne Stroustrup”, as an extension to the C language.
 C++ is a cross-platform language that can be used to create high-performance
applications and software systems.
Tokens:
A token is the smallest element of a program that is meaningful to the compiler. Tokens
can be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keywords: Keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program. Since keywords are
referred names for a compiler, they can’t be used as variable names. You cannot redefine
keywords. C++ language supports 32 keywords which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
While in C++ there are 31 additional keywords other than C Keywords they are:
2. Identifiers: Identifiers are used as the general terminology for the naming of variables,
functions and arrays. These are user-defined names consisting of an arbitrarily long
sequence of letters and digits with either a letter or the underscore (_) as a first character.
You cannot use keywords as identifiers; they are reserved for special use.

There are certain rules that should be followed while naming c++ identifiers:

1. They must begin with a letter or underscore (_).


2. They must consist of only letters, digits, or underscore. No other special character is
allowed.
3. It should not be a keyword.
4. It must not contain white space.
5. It should be up to 31 characters long as only the first 31 characters are significant.

3. Constants: Constants are also like normal variables. But, the only difference is, their
values cannot be modified by the program once they are defined. Constants refer to fixed
values. They are also called literals.
Constants may belong to any of the data type

Syntax:
const data_type variable_name; (or) const data_type *variable_name;

Types of Constants:
1. Integer constants – Example: 0, 1, 1218, 12482
2. Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
3. Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal:
(013)16 = (19)10
4. Character constants -Example: ‘a’, ‘A’, ‘z’
5. String constants -Example: “MSR Degree College”

4. Strings: Strings are nothing but an array of characters ended with a null character (‘\
0’). This null character indicates the end of the string. Strings are always enclosed in
double-quotes. Whereas, a character is enclosed in single quotes in C and C++.

Declarations for String:

char string[20] = {‘I’, ’U’, ‘M’, ‘D’, ‘C’, ‘\0’};


char string[20] = “IUMDC”;
char string [] = “IUMDC”;
when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding
the string value.

When we declare char as “string[]”, memory space will be allocated as per the
requirement during the execution of the program.

5. Special Symbols: The following special symbols are used in C++ having some special
meaning and thus, cannot be used for some other purpose. [] () {}, ; * = #

Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.

Parentheses(): These special symbols are used to indicate function calls and function
parameters.

Braces{}: These opening and ending curly braces mark the start and end of a block of
code containing more than one executable statement.

Comma (, ): It is used to separate more than one statements like for separating parameters
in function calls.

Semicolon(;): It is known as a statement terminator. It indicates the end of one logical


entity. That’s why each individual statement must be ended with a semicolon.

Assignment operator(=): It is used to assign values and for the logical operation
validation.

Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.

6. Operators: Operators are symbols that trigger an action when applied to C++
variables and other objects. The data items on which operators act upon are called
operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:

Unary Operators: Those operators that require only a single operand to act upon are
known as unary operators. For Example increment and decrement operators

Binary Operators: Those operators that require two operands to act upon are called
binary operators. Binary operators are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators

Ternary Operator: The operator that require three operands to act upon are called
ternary operator. Conditional Operator(?) is also called ternary operator.
Syntax: (Expression1)? expression2: expression3;

DATA TYPES:
A data type tells a variable the kind and size of data it can store. When we declare a
variable, the compiler allocates memory for it on the basis of its data type.
In C++, there are three broad categories of data types namely,

1. Fundamental data types


2. Derived data types
3. User-defined data types

Fundamental Data Types in C++


Fundamental (also called Primary or Primitive) data types are the basic built-in or
predefined data types that we can directly use in our programs.

These are of the following types:

Data Type Keyword Size (in Bytes)


Integer int 4
Character char 1
Floating Point float 4
Double Floating Point double 8
Boolean bool 1
1. Integer: C++ int
In C++, int keyword is used for integer data type. It is generally 4 bytes in size ranging
from -2147483648 to 2147483647.

For Example:
int age = 18;

2. Character: C++ char


Characters are represented using the char keyword in C++. It requires 1 byte of memory
space. Its range is from -128 to 127 or 0 to 255.
While declaring a character variable, we need to enclose the character within single
quotes (‘ ’). For example,
char answer = ‘y’;

3. Floating Point: C++ float


We use float to represent floating point (decimal and exponential) values in C++. It is
also known as single-precision floating point data type. float data type requires 4 bytes of
memory space.

For Example:
float area = 34.65;

4. Double Floating Point: C++ double


In C++, we use both float and double to store floating point numbers. But, double has
twice the precision of float and its size is 8 bytes. Hence, it is also called double-precision
floating point data type.

For Example:
double volume = 127.4935;
double value = 25E11; //Exponential 25E9 = 25 * 10^11

5. Boolean: C++ bool


We use bool to store boolean values, which means they can either be true or false. Size of
bool is 1 byte.

For Example:
bool condition = true;

Derived Data Types in C++


Data types that are derived from fundamental data types are called derived data types.
These are of four types in C++ namely, Function, Array, Pointer and Reference.

User-defined Data Types in C++


We, as users, can define data types. These data types defined by the user are referred to as
user-defined data types. Class, Structure, Union, Enumeration and Typedef defined data
type belong to this category.

typedef defined data type


With keyword typedef, we can give a C++ data type a new name.

Syntax:
typedef type newname;
Example of typedef
#include <iostream>
typedef int integer; //we can use integer in place of int
int main()
{
integer total = 100;
cout<<total;
return 0;
}
Output
100

OPERATORS:
An operator is a symbol used for performing operations on operands. An operator
operates operands. The operations can be mathematical or logical. There are different
types of operators in C++ for performing different operations.
Consider the following operation:
a = x + y;
In the above statement, x and y are the operands while + is an addition operator. When
the C++ compiler encounters the above statement, it will add x and y and store the result
in variable a.
There are mainly 6 different types of operators in C++

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators

1. Arithmetic Operators:
These operators are used to perform arithmetic/mathematical operations on operands.
Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:

a) Unary Operators: Operators that operate or work with a single operand are unary
operators. For example: Increment(++) and Decrement(– –) Operators
int val = 5;
++val; // 6
b) Binary Operators: Operators that operate or work with two operands are binary
operators. For example: Addition(+), Subtraction(-), multiplication(*), Division(/)
operators
int a = 7;
int b = 2;
cout<<a+b; // 9

2. Relational Operators:
These are used for the comparison of the values of two operands. For example,
checking if one operand is equal to the other operand or not, an operand is greater than
the other operand or not, etc. Some of the relational operators are (==, >= , <= )
int a = 3;
int b = 5;
a < b; // operator to check if a is smaller than b
3. Logical Operators:
Logical Operators are used to combining two or more conditions/constraints or to
complement the evaluation of the original condition in consideration. The result of the
operation of a logical operator is a Boolean value either true or false.

For example, the logical AND represented as ‘&&’ operator in C or C++ returns true
when both the conditions under consideration are satisfied. Otherwise, it returns false.
Therefore, a && b returns true when both a and b are true

(4 != 5) && (4 < 5); // true

4. Bitwise Operators:
The Bitwise operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the
operands. The mathematical operations such as addition, subtraction, multiplication,
etc. can be performed at bit-level for faster processing. For example, the bitwise
AND represented as & operator in C or C++ takes two numbers as operands and does
AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
(See this article for more reference).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators:
Assignment operators are used to assigning value to a variable. The left side operand of
the assignment operator is a variable and the right side operand of the assignment
operator is a value. The value on the right side must be of the same data type as the
variable on the left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
a. “=”: This is the simplest assignment operator. This operator is used to assign the
value on the right to the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';
b. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds
the current value of the variable on left to the value on the right and then assigns the
result to the variable on the left.
For example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c. “-=”: This operator is a combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the value on the right from the current value of the variable on left and then
assigns the result to the variable on the left.
For example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d. “*=”: This operator is a combination of ‘*’ and ‘=’ operators. This operator first
multiplies the current value of the variable on left to the value on the right and then
assigns the result to the variable on the left.
For example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e. “/=”: This operator is a combination of ‘/’ and ‘=’ operators. This operator first
divides the current value of the variable on left by the value on the right and then
assigns the result to the variable on the left.
For example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators:
Apart from the above operators, there are some other operators available in C or C++
used to perform some specific tasks. Some of them are discussed here:
a. sizeof operator:
1. sizeof is much used in the C/C++ programming language.
2. It is a compile-time unary operator which can be used to compute the size of its
operand.
3. The result of sizeof is of the unsigned integral type which is usually denoted by
size_t.
4. Basically, the sizeof the operator is used to compute the size of the variable
b. Conditional Operator:
1. The conditional operator is of the form Expression1? Expression2: Expression3.
2. Here, Expression1 is the condition to be evaluated. If the condition(Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of
Expression3.
3. We may replace the use of if..else statements with conditional operators.
(See this article for reference)

Expression:
An expression is a combination of operators, constants and variables. An expression
may consist of one or more operands, and zero or more operators to produce a value.
Every expression produces some value which is assigned to the variable with the help of
an assignment operator.
Examples of C++ expression:

1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c
4. (a+b) * (x+y)

Types of Expressions:
Expressions may be of the following types:
o Constant expressions
o Integral expressions
o Float expressions
o Pointer expressions
o Relational expressions
o Logical expressions

 Constant expressions: Constant Expressions consists of only constant values. A


constant value is one that doesn’t change.
Examples:
5, 10 + 5 / 6.0, 'x’
 Integral expressions: Integral Expressions are those which produce integer results
after implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)
where x and y are integer variables.
 Floating expressions: Float Expressions are which produce floating point results
after implementing all the automatic and explicit type conversions.
Examples:
x + y, 10.75
where x and y are floating point variables.
 Relational expressions: Relational Expressions yield results of type bool which
takes a value true or false. When arithmetic expressions are used on either side of a
relational operator, they will be evaluated first and then the results compared.
Relational expressions are also known as Boolean expressions.
Examples:
x <= y, x + y > 2
 Logical expressions: Logical Expressions combine two or more relational
expressions and produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5
 Pointer expressions: Pointer Expressions produce address values.
Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
Arrays in C++:

An array in C++ or be it in any programming language is a collection of similar data


items stored at contiguous memory locations and elements can be accessed randomly
using indices of an array. They can be used to store collection of primitive data types
such as int, float, double, char, etc of any particular type. All arrays consist of
contiguous memory locations. The lowest address corresponds to the first element and
the highest address to the last element.

Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
Ex1:-
// Array declaration by specifying size and initializing elements
int arr[6] = { 10, 20, 30, 40 }

// Compiler creates an array of size 6, initializes first 4 elements as specified by user


and rest two elements as 0.

Ex2:-
// Array declaration by initializing elements
int arr[] = { 10, 20, 30, 40 }

// Compiler creates an array of size 4.


// above is same as "int arr[4] = {10, 20, 30, 40}"

Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size x,y, you would write something as follows −
type arrayName [ x ][ y ];
A two-dimensional array can be think as a table, which will have x number of rows and
y number of columns. A 2-dimensional array a, which contains three rows and four
columns can be shown as below −

Thus, every element in array a is identified by an element name of the form a[ i ][


j ], where a is the name of the array, and i and j are the subscripts that uniquely identify
each element in a.
Initializing Two-Dimensional Arrays
Multidimensioned arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index
and column index of the array. For example −
int val = a[2][3];
The above statement will take 4th element from the 3rd row of the array. You can verify it
in the above digram.
#include <iostream>
void main ()
{ // an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

for ( int i = 0; i < 5; i++ ) // output each array element's value


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

C++ Strings:
String is a collection of characters. There are two types of strings commonly used in C++
programming language:

 Strings that are objects of string class (The Standard C++ Library string class)
 C-strings (C-style Strings)

C-strings

In C programming, the collection of characters is stored in the form of arrays. This is also
supported in C++ programming. Hence it's called C-strings.

C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value
of null character is 0).

char str[] = "C++";

In the above code, str is a string and it holds 4 characters.


Although, "C++" has 3 character, the null character \0 is added to the end of the string
automatically.

Alternative ways of defining a string


char str[4] = "C++";

char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};


Like arrays, it is not necessary to use all the space allocated for the string. For example:
char str[100] = "C++";
C++ program to display a string entered by user.
#include <iostream.h>
void main()
{
char str[100];
cout << "Enter a string: ";
cin >> str;
cout << "You entered: " << str << endl;
cout << "\nEnter another string: ";
cin >> str;
cout << "You entered: "<<str<<endl;
}
C++ string using string data type
#include <iostream.h>
void main()
{
string str; // Declaring a string object
cout << "Enter a string: ";
getline(cin, str);
cout << "You entered: " << str << endl;
getch();
}

Output
Enter a string: Programming is fun.
You entered: Programming is fun.

In this program, a string str is declared. Then the string is asked from the user.

Instead of using cin>> or cin.get() function, you can get the entered line of text
using getline().
getline() function takes the input stream as the first parameter which is cin and str as the
location of the line to be stored.

Pointers:-
The pointer in C++ language is a variable, it is also known as locator or indicator that
points to an address of a value.

Usage of pointer
There are many usage of pointers in C++ language.

1) Dynamic memory allocation


In c language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.

2) Arrays, Functions and Structures


Pointers in c language are widely used in arrays, functions and structures. It reduces the
code and improves the performance.
Declaring a pointer

The pointer in C++ language can be declared using ∗ (asterisk symbol).

int ∗ a; //pointer to int


char ∗ c; //pointer to char
Ex1:-
#include <iostream.h>
void main()
{

int ∗ p;
int number=30;

p=&number;//stores the address of number variable


cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
getch();
}
Ex2:-
#include <iostream>
int main()
{

cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;


int a=20,b=10,∗p1=&a,∗p2=&b;

∗p1=∗p1+∗p2;
∗p2=∗p1-∗p2;
∗p1=∗p1-∗p2;
cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
getch();
}

Sorting Techniques In C++


Sorting is a technique that is implemented to arrange the data in a specific order. Sorting
is required to ensure that the data which we use is in a particular order so that we can
easily retrieve the required piece of information from the pile of data.
Sorting Techniques In C++
C++ supports various sorting techniques as listed below.

Bubble Sort
Bubble sort is the simplest technique in which we compare every element with its
adjacent element and swap the elements if they are not in order. This way at the end of
every iteration (called a pass), the heaviest element gets bubbled up at the end of the list.

implement Bubble Sort technique in C++.


#include<iostream.h>
void main ()
{
int i, j,temp;
int a[5] = {10,2,0,43,12};
cout <<"Input list ...\n";
for(i = 0; i<5; i++)
{
cout <<a[i]<<"\t";
}
cout<<endl;
for(i = 0; i<5; i++)
{
for(j = i+1; j<5; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
cout <<"Sorted Element List ...\n";
for(i = 0; i<5; i++)
{
cout <<a[i]<<"\t";
}
getch();
}

Functions in C++:-
A function is a group of statements that together perform a task. Every C++ program has
at least one function, which is main().
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.

There are two types of function:

1. Standard Library Functions: Predefined in C++


2. User-defined Function: Created by users

Syntax:
return_type function_name( parameter list )
{
body of the function
}

A C++ function definition consists of a function header and a function body. Here are all
the parts of a function −
 Return Type − A function may return a value. The return_type is the data type
of the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
 Function Body − The function body contains a collection of statements that
define what the function does.
Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
Syntax:
return_type function_name( parameter list );

Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To
use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when it’s return statement is executed or when
its function-ending closing brace is reached, it returns program control back to the main
program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value.
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
Default Values for Parameters
When you define a function, you can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when
calling to the function.
This is done by using the assignment operator and assigning values for the arguments in
the function definition. If a value for that parameter is not passed when the function is
called, the default given value is used, but if a value is specified, this default value is
ignored and the passed value is used instead.

Ex:-
#include <iostream>
int sum(int,int); // function prototype
int main ()
{
int a = 100; // local variable declaration:
int b = 200;
int result;

result = sum(a, b); // calling a function to add the values.


cout << "Total value is :" << result << endl;

result = sum(a); // calling a function again as follows.


cout << "Total value is :" << result << endl;
getch();
}
int sum(int a, int b = 20) // function definition
{
int result;
result = a + b;
return (result);
}

C++ Inline Functions


C++ inline function is powerful concept that is commonly used with classes. If a
function is inline, the compiler places a copy of the code of that function at each point
where the function is called at compile time.
Any change to an inline function could require all clients of the function to be
recompiled because compiler would need to replace all the code once again otherwise it
will continue with old functionality.
To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline
qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without
the use of the inline specifier.
#include <iostream>
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
int main() // Main function for the program
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
getch();
}
Passing Array to a Function in C++
In C++, we can pass arrays as an argument to a function. And, also we can return arrays
from a function.

Syntax
returnType functionName(dataType arrayName[arraySize])
{
// code
}
Let's see an example,
int total(int marks[5])
{
// code
}
Passing One-dimensional Array to a Function
// C++ Program to display marks of 5 students
#include <iostream>
void display(int m[5]) // declare function to display marks take a 1d array as parameter
{
cout << "Displaying marks: " << endl;
for (int i = 0; i < 5; ++i) // display array elements
{
cout << "Student " << i + 1 << ": " << m[i] << endl;
}
}

int main() {
int marks[5] = {88, 76, 90, 61, 69}; // declare and initialize an array
// call display function pass array as argument
display(marks);
getch();
}

Differences between Procedural and Object Oriented Programming.


Both Procedural Oriented Programming (POP) and Object Oriented Programming (OOP)
are the high level languages in programming world and are widely used in development
of applications. On the basis of nature of developing the code both languages have
different approaches on basis of which both are differentiate from each other.
Following are the important differences between Procedural Oriented Programming
(POP) and Object Oriented Programming (OOP)

Sr. Object Oriented Programming Procedural Oriented Programming


Key
No. (OOP) (POP)
1 Definition Object-oriented Programming is On other hand Procedural Oriented
a programming language that Programming is a programming
uses classes and objects to create language that follows a step-by-step
models based on the real world approach to break down a task into a
environment. In OOPs it makes collection of variables and routines (or
it easy to maintain and modify subroutines) through a sequence of
existing code as new objects are instructions. Each step is carried out in
created inheriting characteristics order in a systematic manner so that a
from existing ones. computer can understand what to do.
2 Approach In OOPs concept of objects and On other hand in case of POP the main
classes is introduced and hence program is divided into small parts
the program is divided into small based on the functions and is treated as
chunks called objects which are separate program for individual smaller
instances of classes. program.
3 Access In OOPs access modifiers are On other hand no such modifiers are
modifiers introduced namely as Private, introduced in POP.
Public and Protected
4 Security Due to abstraction in OOPs data On other hand POP is less secure as
hiding is possible and hence it is compare to OOPs.
more secure than POP.
5 Complexity OOPs due to modularity in its On other hand no simple process to add
programs is less complex and data in POP at least not without
hence new data objects can be revising the whole program.
created easily from existing
objects making object-oriented
programs easy to modify
OOP Features:
The major purpose of C++ programming is to introduce the concept of object orientation
to the C programming language.
Object Oriented Programming is a paradigm that provides many concepts such
as inheritance, data binding, polymorphism etc.

Object
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects.
An object contains data and methods or functions that operate on that data. Objects take
up space in memory.
It simplifies the software development and maintenance by providing some concepts:

Class
A class, on the other hand, is a blueprint of the object. Conversely, an object can be
defined as an instance of a class. A class contains a skeleton of the object and does not
take any space in the memory.It is a logical entity.

Abstraction
Data abstraction refers to, providing only essential information to the outside world and
hiding their background details, i.e., to represent the needed information in program
without presenting the details.
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.
Encapsulation

Binding (or wrapping) code and data together into a single unit is known as
encapsulation.

Encapsulation is placing the data and the functions that work on that data in the same
place. While working with procedural languages, it is not always clear which functions
work on which variables but object-oriented programming provides you framework to
place the data and the relevant functions together in the same object.

Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As
the name suggests 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.
This is a very important concept of object-oriented programming since this feature helps
to reduce the code size.
Polymorphism
Polymorphism means many forms.Polymorphism is an important feature of OOP and is
usually implemented as operator overloading or function overloading. Operator
overloading is a process in which an operator behaves differently in different situations.
Similarly, in function overloading, the same function behaves differently in different
situations.
Class in C++:
A class is a user-defined data type representing a group of similar objects, which holds
member functions and variables together. We can define classes using the keyword
‘class’ followed by the name of the class. The body of class is defined inside the curly
brackets and terminated by a semicolon at the end.

Declaring Objects:
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need
to create objects.
Syntax:
ClassName ObjectName;

Accessing data members and member functions: The data members and member
functions of class can be accessed using the dot(‘.’) operator with the object. For
example if the name of object is obj and you want to access the member function with
the name printName() then you will have to write obj.printName() .

Access modifiers:

These are the specifiers which provide or grant access for the members.
They are of three types:
Private: Only members of the same class have access to private members.

Public: You can access the public members from within, as well as from outside of the
class.

Protected: You can access the protected members from the same class members and
members of the derived class. It is also accessible from outside the class but with the help
of the friend function.

// C++ program to demonstrate accessing of data members


#include <iostream.h>
#inlcude<conio.h>
class Demo {
public: // Access specifier
string name; // Data Members
void printname() // Member Functions()
{
cout << "Name is:" << name;
}
};
void main()
{
Demo obj1; // Declare an object of class geeks
obj1.name = "Abhi"; // accessing data member
obj1.printname(); // accessing member function
getch();
}

Member Functions in Classes:

There are 2 ways to define a member function:


 Inside class definition
 Outside class definition
To define a member function outside the class definition we have to use the scope
resolution :: operator along with class name and function name.

// C++ program to demonstrate function declaration outside class


#include <iostream.h>
#include<conio.h>
class Sample
{
public:
string name;
int id;
void printname(); // printname is not defined inside class definition
void printid() // printid is defined inside class definition
{
cout <<"Id is: "<<id;
}
};
void Sample::printname() // Definition of printname using scope resolution operator ::
{
cout <<"Name is: "<<name;
}
void main()
{
Sample obj1;
obj1.name = "xyz";
obj1.id=15;
obj1.printname(); // call printname()
cout << endl;
obj1.printid(); // call printid()
getch();
}

Inline function in C++


C++ inline function is powerful concept that is commonly used with classes. If a function
is inline, the compiler places a copy of the code of that function at each point where the
function is called at compile time.
To inline a function, place the keyword “inline” before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline
qualifier in case defined function is more than a line.

Syntax:
inline return_type function_name(parameters)
{
// function code?
}

Ex:
#include<iostream.h>
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
return 0;
}

Note:
We cannot provide the inlining to the functions in the following circumstances:
o If a function is recursive.
o If a function contains a loop like for, while, do-while loop.
o If a function contains static variables.

o If a function contains a switch or go to statement

C++ Constructor
1. Constructor in C++ is a special method that is invoked automatically at the time of
object creation.
2. It is used to initialize the data members of new objects generally.
3. The constructor in C++ has the same name as the class or structure.
4. Constructor is invoked at the time of object creation.
5. Constructor does not have a return value, hence they do not have a return type.
6. Constructors can be defined inside or outside the class declaration.

The following syntax is used to define the class's constructor:


<class-name> (list-of-parameters)
{
// constructor definition
}

The following syntax is used to define a constructor outside of a class:


<class-name>: :<class-name> (list-of-parameters)
{
// constructor definition
}

Characteristics of the constructor:


 Constructors are mostly declared in the public section of the class though it can be
declared in the private section of the class.
 Constructors do not return values; hence they do not have a return type.
 A constructor gets called automatically when we create the object of the class.
 Constructors can be overloaded.
 Constructor cannot be declared virtual.
 Constructor cannot be inherited.

There can be two types of constructors in C++.


o Default constructor
o Parameterized constructor

Default Constructors:
Default constructor is the constructor which doesn’t take any argument. It has no
parameters. It is also called a zero-argument constructor.
// Cpp program to illustrate the concept of Constructors
#include <iostream.h>
class construct
{
public:
int a, b;

construct() // Default Constructor


{
a = 10;
b = 20;
}
};
int main()
{
construct c; // Default constructor called automatically when the object is created
cout << "a: " << c.a << endl << "b: " << c.b;
}

Parameterized Constructors:
A constructor which has parameters is called parameterized constructor. It is used to
provide different values to distinct objects.
#include <iostream>
class Employee
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main()
{
Employee e1 =Employee(101, "Sonoo", 890000);
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with an
object of the same class, which has been created previously. The copy constructor is used
to −
 Initialize one object from another of the same type.
 Copy an object to pass it as an argument to a function.
 Copy an object to return it from a function.
Syntax:
classname (const classname &obj)
{
// body of constructor
}
Ex:
#include<iostream>
class Number
{
int a;
public:

Number()
{
a = 0;
}
Number(int num)
{
a = num;
}
// When no copy constructor is found, compiler supplies its own copy constructor
Number(Number &obj)
{
cout<<"Copy constructor called!!!"<<endl;
a = obj.a;
}
void display()
{
cout<<"The number for this object is "<< a <<endl;
}
};
int main()
{
Number x, y, z(45), z2;
x.display();
y.display();
z.display();
Number z1(z); // Copy constructor invoked
z1.display();
getch();
}

Constructor Overloading
In C++, We can have more than one constructor in a class with same name, as long as
each has a different list of arguments. This concept is known as Constructor Overloading
and is quite similar to function overloading.

 Overloaded constructors essentially have the same name (exact name of the class)
and different by number and type of arguments.
 A constructor is called depending upon the number and type of arguments passed.
 While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.

Ex:
#include <iostream>
class Complex
{
int a, b;
public:
Complex()
{
a = 0;
b =0;
}
Complex(int x, int y)
{
a = x;
b = y;
}
Complex(int x)
{
a = x;
b = 0;
}
void printNumber()
{
cout << "Your number is " << a << " + " << b << "i" << endl;
}
};
int main()
{
Complex c1(4, 6);
c1.printNumber();

Complex c2(5);
c2.printNumber();

Complex c3;
c3.printNumber();
return 0;
}

Destructor:
Destructor is an instance member function which is invoked automatically whenever an
object is going to be destroyed. Meaning, a destructor is the last function that is going
to be called before an object is destroyed.
 Destructor is also a special member function like constructor. Destructor destroys the
class objects created by constructor.
 Destructor has the same name as their class name preceded by a tilde (~) symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object create by constructor. Hence
destructor can-not be overloaded.
 Destructor neither requires any argument nor returns any value.
 It is automatically called when object goes out of scope.
 Destructor release memory space occupied by the objects created by constructor.
Syntax:
Syntax for defining the destructor within the class
~ <class-name>()
{
}
Syntax for defining the destructor outside the class
<class-name>: : ~ <class-name>()
{
}
Ex:
#include<iostream>
class Test
{
public:
Test()
{
cout<<"\n Constructor executed";
}
~Test()
{
cout<<"\n Destructor executed";
}
};
void main()
{
Test t;
return 0;
}
Static data members:
Static data members are class members that are declared using static keywords. A static
member has certain special characteristics. These are:
 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 initialized before any object of this class is being created, even before main
starts.
 It is visible only within the class, but its lifetime is the entire program
#include <iostream>
class Example
{
static int x;
public:
void function1()
{
x++;
}
void function2()
{
cout<<"x = "<<x<<"\n";
}
};
int Example :: x=0;
int main()
{
Example obj1, obj2, obj3;
cout<<"Initial value of x" <<"\n";
obj1.function2();
obj2.function2();
obj3.function2();

obj1.function1();
obj2.function1();
obj3.function1();

cout<<"Value of x after calling function1"<<"\n";


obj1.function2();
obj2.function2();
obj3.function2();

getch();
}
C++ Inheritance
1. Inheritance is one of the most important features of Object-Oriented Programming.
2. In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically.
3. Inheritance is a feature or a process in which, new classes are created from the
existing classes.
4. The new class created is called “derived class” or “child class” and the existing class
is known as the “base class” or “parent class”. The derived class now is said to be
inherited from the base class.
Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}

Types Of Inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

Single Inheritance:
In single inheritance, a class is allowed to inherit from only one class. i.e. one
subclass is inherited by one base class only.
Syntax:
class A
{ ... .. ...
};
class B: public A
{... .. ...
};
Ex:
#include<iostream>
class A
{
protected:
int a;
public:
void set_A()
{
cout<<"Enter the Value of A=";
cin>>a;
}
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};
class B: public A
{
int b,p;
public:
void set_B()
{
set_A();
cout<<"Enter the Value of B=";
cin>>b;
}
void disp_B()
{
disp_A();
cout<<endl<<"Value of B="<<b;
}
void cal_product()
{
p=a*b;
cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;
}
};
main()
{
B _b;
_b.set_B();
_b.cal_product();
return 0;
}

Multiple Inheritance:
Multiple Inheritance is a feature of C++ where a class can inherit from more than
one class. i.e one subclass is inherited from more than one base class.
Syntax:
class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};
Here, the number of base classes will be separated by a comma (‘, ‘) and the access
mode for every base class must be specified.
Ex:
#include<iostream.h>
#include<conio.h>
class Father
{
public:
void fatherMethod()
{
cout<<"from father method"<<endl;
}
};
class Mother
{
public:
void motherMethod()
{
cout<<"from mother method"<<endl;
}
};
class Ch1:public Father,public Mother
{
public:
void child1()
{
cout<<"from child1"<<endl;
}
};
void main()
{
clrscr();
Ch1 obj1;
obj1.fatherMethod();
obj1.motherMethod();
obj1.child1();
getch();
}

Multilevel Inheritance:
In this type of inheritance, a derived class is created from another derived class.
Syntax:-
class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};
Ex:
#include<iostream>
class A
{
protected:
int a;
public:
void set_A()
{
cout<<"Enter the Value of A=";
cin>>a;
}
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};
class B: public A
{
protected:
int b;
public:
void set_B()
{
cout<<"Enter the Value of B=";
cin>>b;
}
void disp_B()
{
cout<<endl<<"Value of B="<<b;
}
};
class C: public B
{
int c,p;
public:
void set_C()
{
cout<<"Enter the Value of C=";
cin>>c;
}
void disp_C()
{
cout<<endl<<"Value of C="<<c;
}
void cal_product()
{
p=a*b*c;
cout<<endl<<"Product of "<<a<<" * "<<b<<" * "<<c<<" = "<<p;
}
};
main()
{
C obj;
obj.set_A();
obj.set_B();
obj.set_C();
obj.disp_A();
obj.disp_B();
obj.disp_C();
obj.cal_product();
return 0;
}
Hierarchical Inheritance: In this type of inheritance, more than one subclass is
inherited from a single base class. i.e. more than one derived class is created from a
single base class.
Syntax:-
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Ex:
#include<iostream.h>
#include<conio.h>
class Parent
{
public:
void parentMethod()
{
cout<<"from parent"<<endl;
}
};
class Ch1:public Parent
{
public:
void child1()
{
cout<<"from child1"<<endl;
}
};
class Ch2:public Parent
{
public:
void child2()
{
cout<<"from child2"<<endl;
}
};
void main()
{
clrscr();
Ch1 obj1;
obj1.parentMethod();
obj1.child1();
Ch2 obj2;
obj2.parent();
obj2.child2();
getch();
}

Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more


than one type of inheritance. For example: Combining Hierarchical inheritance and
Multiple Inheritance.

Access Modifiers in C++


Data hiding is an important concept of Object-Oriented Programming, implemented with
these Access modifiers' help. It is also known as Access Specifier.

Access Specifiers in a class decide the accessibility of the class members, like variables
or methods in other classes. That is, it will decide whether the class members or methods
will get directly accessed by the blocks present outside the class or not, depending on the
type of Access Specifier.

In a program, we need to create methods or variables that can be accessed by the object
of the same class or accessible in the entire program. And Access Modifiers help us to
specify that.
Syntax:
class ClassName
{
private:
// Declare private members/methods here.
public:
// Declare public members/methods here.
protected:
// Declare protected members/methods here.
};
There are three types of access modifiers in C++:
1. Public
2. Private
3. Protected

1. Public Access Specifier


This keyword is used to declare the functions and variables public, and any part of the
entire program can access it. The members and member methods declared public can be
accessed by other classes and functions.

The public members of a class can be accessed from anywhere in the program using
the (.) with the object of that class.

Ex:
// C++ program to demonstrate public access modifier
#include<iostream.h>
#include<conio.h>
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
void main()
{
clrscr();
Circle obj;
// accessing public datamember outside class
obj.radius = 5.5;
cout << "Radius is: " << obj.radius << "\n";
cout << "Area is: " << obj.compute_area();
getch();
}
2. Private Access Specifiers
The private keyword is used to create private variables or private functions. The private
members can only be accessed from within the class. Only the member functions or the
friend functions are allowed to access the private data of a class or the methods of a class.
Note -

Protected and Private data members or class methods can be accessed using a function
only if that function is declared as the friend function.

We can use the keyword friend to ensure the compiler understands and make the data
accessible to that function.

Ex:
// C++ program to demonstrate private access modifier
#include<iostream.h>
#include<conio.h>
class Circle
{
private: // private data member
double radius;
public: // public member function
void compute_area(double r)
{
radius = r; // member function can access private data member radius
double area = 3.14*radius*radius;
cout << "Radius is: " << radius << endl;
cout << "Area is: " << area;
}
};
void main()
{
Circle obj; // creating object of the class
// trying to access private data member directly outside the class like obj.radius=1.5
obj.compute_area(1.5);
getch();
}

3. Protected Access Specifiers

The protected keyword is used to create protected variables or protected functions. The protected
members can be accessed within and from the derived/child class.
Note - A class created or derived from another existing class(base class) is known as a derived
class. The base class is also known as a superclass. It is created and derived through the process
of inheritance.

Ex:
// C++ program to demonstrate protected access modifier
#include<iostream.h>
#include<conio.h>
class A
{
protected:
int a;
public:
void method1(int x)
{
a=x;
cout<<"a value:"<<a<<endl;
}
};
void main()
{
clrscr();
A obj;
//obj.a=100;
obj.method1(100);
getch();
}

Streams:
 A C++ stream is a flow of data into or out
of a program, such as the data written to cout or read from cin.
 Stream classes in C++ are used to input and output operations on files and io devices.
 These classes have specific features and to handle input and output of the program.
All these classes are defined in the file iostream.h.

For this class we are currently interested in four different classes:

 istream is a general purpose input stream. cin is an example of an istream.


 ostream is a general purpose output stream. cout and cerr are both examples of
ostreams.
 ifstream is an input file stream. It is a special kind of an istream that reads in data
from a data file.
 ofstream is an output file stream. It is a special kind of ostream that writes data
out to a data file.

C++ Polymorphism:
The term "Polymorphism" is the combination of
"poly" + "morphs" which means many forms. It is a
greek word. A real-life example of polymorphism is a
person at the same time is a father, a husband, and an
employee. So the same person exhibits different
behavior in different situations. This is called
polymorphism. Polymorphism is considered one of
the important features of Object-Oriented
Programming.
Types of Polymorphism
 Compile-time Polymorphism.
 Runtime Polymorphism.

1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator
overloading.

A. Function Overloading

When there are multiple functions with the same name but different parameters, then
the functions are said to be overloaded, hence this is known as Function Overloading.
Functions can be overloaded by changing the number of arguments or/and changing
the type of arguments.
Ex:
// C++ program to demonstrate function overloading or Compile-time Polymorphism
#include <iostream.h>
class Polymorphism
{
public:
void func(int x) // Function with 1 int parameter
{
cout << "value of x is " <<x << endl;
}
void func(double x) // Function with same name but 1 double parameter
{
cout << "value of x is " <<x << endl;
}
void func(int x, int y) // Function with same name and 2 int parameters
{
cout << "value of x and y is " <<x << ", " << y << endl;
}
};
int main()
{
Polymorphism obj1;
obj1.func(7); // Function being called depends on the parameters
obj1.func(9.132); // func() is called with double value
obj1.func(85, 64); // func() is called with 2 int values
return 0;
}

B. Operator Overloading
Using operator overloading in C++, you can specify more than one meaning for an
operator in one scope. The purpose of operator overloading is to provide a special
meaning of an operator for a user-defined data type. You can also use operator
overloading to perform different operations using one operator.

For example, we can make use of the addition operator (+) for string class to
concatenate two strings. We know that the task of this operator is to add two operands.
So a single operator ‘+’, when placed between integer operands, adds them and when
placed between string operands, concatenates them.
Syntax:
To overload a C++ operator, you should define a special function inside the Class as
follows:
class class_name
{
... .. ...
public
return_type operator symbol (argument(s))
{
... .. ...
}
... .. ...
};
Ex:
#include <iostream.h>
class OverLoad
{
private:
int a,b;
public:
OverLoad()
{
a=0; b=0;
}
void in()
{
cout << "Enter the first number : ";
cin >> a;
cout<< "Enter the second number : ";
cin >> b;
}
// Overload the prefix decrement operator
void operator-- ()
{
a= a+10;
b= b+10;
}
void out()
{
cout<<"The decremented elements of the object are: "<<endl<< a<<" and
" <<b;
}
};
int main()
{
OverLoad obj;
obj.in();
--obj;
obj.out();
return 0;
}

2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and
dynamic polymorphism are other names for runtime polymorphism. The function call is
resolved at runtime in runtime polymorphism. In contrast, with compile time
polymorphism, the compiler determines which function call to bind to the object after
deducing it at runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.

// C++ program for function overriding


#include <iostream.h>
class base
{
public:
virtual void print()
{
cout << "print base class" <<endl;
}
void show()
{
cout << "show base class" <<endl;
}
};
class derived : public base
{
public:
// print () is already virtual function in derived class, we could also declared as
virtual void print () explicitly
void print()
{
cout << "print derived class" << endl;
}
void show()
{
cout << "show derived class" <<endl;
}
};
int main() // Driver code
{
base* bptr;
derived d;
bptr = &d;
// Virtual function, binded at runtime (Runtime polymorphism)
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
Virtual Function
A virtual function is a member function that is declared in the base class using the
keyword virtual and is re-defined (Overridden) in the derived class.
Some Key Points About Virtual Functions:
 Virtual functions are Dynamic in nature.
 They are defined by inserting the keyword “virtual” inside a base class and are
always declared with a base class and overridden in a child class
 A virtual function is called during Runtime

Ex:
// C++ Program to demonstrate the Virtual Function
#include <iostream>
class Base // Declaring a Base class
{
public:
virtual void display() // virtual function
{
cout << "Called virtual Base Class function" <<"\n\n";
}
void print()
{
cout << "Called Base print function" <<"\n\n";
}
};
class Child : public Base // Declaring a Child Class
{
public:
void display()
{
cout << "Called Child Display Function" <<"\n\n";
}
void print()
{
cout << "Called Child print Function" <<"\n\n";
}
};
int main() // Driver code
{
Base* base; // Create a reference of class GFG_Base
Child child;
base = &child;
base->Base::display(); // This will call the virtual function
base->print(); // this will call the non-virtual function
}

Exception Handling in C++:


An exception is a problem that arises during the execution of a program. A C++
exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.
Exceptions are runtime anomalies or abnormal conditions that a program encounters
during its execution.
Errors can be broadly categorized into two types. We will discuss them one by one.

1. Compile Time Errors


2. Run Time Errors
Compile Time Errors – Errors caught during compiled time is called Compile time
errors. Compile time errors include library reference, syntax error or incorrect class
import.

Run Time Errors - They are also known as exceptions. An exception caught during run
time creates serious issues.

Errors restrict the normal execution of program. Exception handling is the process of
handling errors and exceptions in such a way that they do not hinder normal execution of
the system. For example, User divides a number by zero, this will compile successfully
but an exception or run time error will occur due to which our applications will be
crashed. In order to avoid this we'll introduce exception handling techniques in our code.

In C++, Error handling is done using three keywords:

 try
 catch
 throw

Syntax:
try
{
//code
throw parameter;
}
catch(exceptionname ex)
{
//code to handle exception
}

try block:

The code which can throw any exception is kept inside(or enclosed in) a try block. Then,
when the code will lead to any error, that error/exception will get caught inside
the catch block.

catch block:

catch block is intended to catch the error and handle the exception condition. We can
have multiple catch blocks to handle different types of exception and perform different
actions when the exceptions occur. For example, we can display descriptive messages to
explain why any particular exception occurred.

Syntax:

try {
// protected code
}
catch( ExceptionName e )
{
// code to handle ExceptionName exception
}

throw statement:

It is used to throw exceptions to exception handler i.e. it is used to communicate


information about error. A throw expression accepts one parameter and that parameter is
passed to handler.

throw statement is used when we explicitly want an exception to occur, then we can
use throw statement to throw or generate that exception.

Syntax:

try
{
throw 'a';
}
catch (int x)
{
cout << "Caught " << x;
}

Ex:
#include <iostream.h>
#include<conio.h>
void main()
{
int a=10, b=0, c;
try // try block activates exception handling
{
if(b == 0)
{
// throw custom exception
throw "Division by zero not possible";
c = a/b;
}
}
catch(char* ex) // catches exception
{
cout<<ex;
}
getch();
}

Re-throwing an Exception:
In C++, we can re-throw an exception that was caught in a try-catch block by using the
throw keyword without any argument.

Ex:
#include <iostream.h>
#include<conio.h>
int main()
{
try {
try {
throw 20;
}
catch (int n) {
cout << "Handle Partially ";
throw; // Re-throwing an exception
}
}
catch (int n) {
cout << "Handle remaining ";
}
return 0;
}

Multiple Exceptions:
In C++, you can handle multiple exceptions using a try-catch block with multiple catch
statements. Each catch statement can handle a specific type of exception, allowing you to
perform different actions based on the type of exception that is thrown.
Syntax:

try {
// protected code
}
catch( ExceptionName1 e1 )
{
// code to handle ExceptionName exception
}
catch(ExceptionName2 e2)
{
//code to handle ExceptionName exception
}

Ex:

#include <iostream.h>
#include<conio.h>
void main()
{
int numerator, denominator, res,arr[4] = {10, 20, 30, 40};
int index;
cout << "Enter array index: ";
cin >> index;

try
{
if (index >= 4) // throw exception if array out of bounds
{ // not executed if array is out of bounds
throw "Error: Array out of bounds!";
}
else
{
cout<<”Array value:”<<arr[index]<<endl;
}
cout << "Enter numerator: ";
cin >> numerator;

cout << "Enter denominator: ";


cin >> denominator;

// throw exception if denominator is 0


if (denominator == 0)
throw 0; // not executed if denominator is 0
res = numerator / denominator;
cout <<”Result:”<< res << endl;
}
catch (const char* msg) // catch "Array out of bounds" exception
{
cout << msg << endl;
}
catch (int num) // catch "Divide by 0" exception
{
cout << "Error: Cannot divide by " << num << endl;
}
// catch any other exception
catch (...)
{
cout << "Unexpected exception!" << endl;
}
getch();
}
C++ Templates:
A C++ template is a powerful feature added to C++. It allows you to define the generic
classes and generic functions and thus provides support for generic programming.
Generic programming is a technique where generic types are used as parameters in
algorithms so that they can work for a variety of data types.

Templates can be used to define functions, classes and other constructs that can operate
on a variety of data types without having to rewrite the code for each type.
C++ adds two new keywords to support
templates: ‘template’ and ‘type name’.
The second keyword can always be
replaced by the keyword ‘class’.

Templates are expanded at compiler


time. The compiler does type-checking
before template expansion. The idea is
simple, source code contains only
function/class, but compiled code may
contain multiple copies of the same
function/class.

Templates can be represented in two ways:

o Function templates
o 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.

Syntax:
template <typename T>
T functionName(T parameter1, T parameter2, ...)
{
// code
}

Ex:
#include<iostream.h>
#include<conio.h>
template <class t>
t sum(t a,t b)
{
cout<<"Total:"<<(a+b)<<endl;
}
void main()
{
clrscr();
sum(10,20);
}

Function Templates with Multiple Parameters


We can use more than one generic type in the template function by using the comma to
separate the list.

Syntax:
template<class T1, class T2,…..>
return_type function_name (arguments of type T1, T2….)
{
//body of function.
}

Ex:
#include<iostream.h>
#include<conio.h>
template <class t1,class t2,class t3>
void show(t1 a,t2 b,t3 c)
{
cout<<"a value:"<<a<<endl;
cout<<"b value:"<<b<<endl;
cout<<"c value:"<<c<<endl;
}
void main()
{
clrscr();
show(10,20.34,'c');
getch();
}
Template Function Overloading:
 The name of the function templates are the same but called with different arguments
is known as function template overloading.
 If the function template is with the ordinary template, the name of the function
remains the same but the number of parameters differs.
 When a function template is overloaded with a non-template function, the function
name remains the same but the function’s arguments are unlike.

Ex:
// C++ program to illustrate overloading of template function using an explicit function
#include<iostream.h>
#include<conio.h>
template <class T>
void display(T t1) //Template overloading of function
{
cout << "Displaying Template: "<< t1 << "\n";
}
void display(int t1) //Template overloading of function
{
cout << "Explicitly display: "<< t1 << "\n";
}
int main()
{
// Function Call with a different arguments
display(200);
display(12.40);
display('G');
return 0;
}

Class Templates
Class templates like function templates, class templates are useful when a class defines
something that is independent of the data type.
Syntax of Class Template
template<class Ttype>
class class_name
{
//class body;
}
Here Type is a placeholder type name, which will be specified when a class instantiated.
The Type can be used inside the body of the class.

Ex:
#include<iostream.h>
#include<conio.h>
template <class t>
class Demo
{
private:
t num1,num2;
public:
Demo(t n1,t n2)
{
num1=n1;
num2=n2;
}
void check()
{
if(num1>num2)
{
cout<<num1<<" is the largest value"<<endl;
}
else
{
cout<<num2<<" is the largest value"<<endl;
}
}
};

void main()
{
clrscr();
Demo <int>obj1(5,3);
Demo <float>obj2(10.23,20.35);
obj1.check();
obj2.check();
getch();
}

STL in C++:
In C++, the C++ STL is a very powerful feature and it is a set of C++ template classes.
With the help of STL, you can make use of general-purpose classes and functions with
templates. And these implement many popular and most used algorithms and data
structures like vectors, lists, queues and stacks.

The C++ Standard Template Library (STL) is a collection of algorithms, data structures,
and other components that can be used to simplify the development of C++ programs.
The STL provides a range of containers, such as vectors, lists, and maps, as well as
algorithms for searching, sorting and manipulating data.

One of the key benefits of the STL is that it provides a way to write generic, reusable
code that can be applied to different data types. This means that you can write an
algorithm once, and then use it with different types of data without having to write
separate code for each type.

STL has 4 components:

 Algorithms
 Containers
 Function objects
 Iterators

You might also like