0% found this document useful (0 votes)
20 views145 pages

c++ Material Vijitha (1)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views145 pages

c++ Material Vijitha (1)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 145

CHAPTER-1

INTRODUCTION TO C++
• Multi-paradigm Language- C++ supports at least seven different styles of programming.
Developer can choose any of the styles.
• General purpose language- helps to develop games, desktop applications, operating
systems and so on.
• Speed- the performance of optimized C++ code is exceptional.
• Object oriented programming- allows us to divide complex problems into smaller sets
by using objects.

WHY USE C++:

1
DIFFERENCE BETWEEN C AND C++:

2
CHAPTER-2
REQUIREMENTS TO START C++:

• There are two main things


1. Text editor.
2. A compiler like GCC to convert C++ code into a language that the computer will
understand.
3. Install IDE-(Integrated Development Environment)
• Used to compile and edit the code.
• IDE like eclipse, visual studio etc.,

3
CHAPTER-3

C++ SYNTAX
First program:
#include<iostream>
using namespace std;
int main()
{
cout<<“WELCOME”;
Return 0;
}
1. #include<iostream>
➢ First line of every C++ program Header File Library.
➢ C++ works with input and output objects.
➢ Header files add functionality to C++ programs.
2. using namespace std
➢ It means we can use names for objects and variables from the standard library.
3. blank line.
➢ C++ ignores blank space.
➢ It is used for make the code more readable.
4. int main()
➢ This is a function.
➢ The code which is inside the {}(curly brackets) executed first in C++ program.
5. Cout
➢ It is an object used together with insertion operator(<<) to output/print text.
6. return 0
➢ Ends the main function

Omitting namespace
• Some C++ program runs without the standard namespace Library.
• It can be replaced with std keyword followed by the (::) operator for some objects.
For example:
#include<iostream>

4
Int main()
{
Std::cout<<“Hello”;
Return 0;
}
Note: it up to the user may want to use standard namespace library or not.

C++ main() function:


• In almost every C++ program there is a main() function and every other function is called
or implemented through main().
• main() function is an entry point for a C++ program. We give the system access to our
C++ code through the main() function.
Header Files:
Preprocessor directives:
• Preprocessor directives (those that begin by #) are out of this general rule since they are
not statements.
• They are lines read and processed by the preprocessor and do not produce any code by
themselves.
• Preprocessor directives must be specified in their own line and do not have to end with
a semicolon (;).

Basic input/output using cin and cout:


Cin
• The cin is a predefined object of istream class.
• It is connected with the standard input device, which is usually a keyboard.
The cin is used in conjunction with stream extraction operator (>>) to read the input from a
console.

Cout
• The cout is a predefined object of ostream class.
• It is connected with the standard output device, which is usually a display screen.
• The cout is used in conjunction with stream insertion operator (<<) to display the output
on a console.

Tokens:
• Token is a smallest element of a program that is meaningful to compiler.

5
• Tokens can be classified as follows:
• Keywords
• Identifiers
• Constants
• Strings
• Special symbols
• operators

keywords:
• Keywords are pre-defined or reserved words in a programming Language.
• Each keyword is meant to perform a specific function in a program.
• Keywords are referred names for a compiler.
• We cannot redefine keywords.

Identifiers:
• Identifiers are the unique names given to variables, classes, functions or other entities
by the programmer.
Example:
int money;
double accountBalance;
Here money and accountBalance are identifiers.

Rules for naming identifiers:


• Identifiers can be composed of letters, digits, and the underscore character.

6
• It has no limit on name length.
• It must begin with either a letter or an underscore.
• It is case-sensitive.
• We cannot use keywords as identifiers.

7
CHAPTER-4
Comments:
• Comments are hints that a programmer can add to make their code easier to read and
understand.
• There are completely ignored by compiler.
• There are two ways to add comments to code:
• //-single line comments.
• Example: int a //declaring a variable.
• /* */ - /Multiline comments.
• Example:
/* declaring a variable to store
salary to employees */
int salary = 2000;
why use comments?:
• If we write comments on our code, it will be easier for us to understand the code in the
future.
• Also, it will be easier for your fellow developers to understand the code.

Note: comments shouldn’t be the substitute for a way to explain poorly written code in
English. We should always write well-structured an self explanatory code. And, then use
comments.

8
CHAPTER-5

Variables:

• Variable is a container(storage area) to hold data.

• To indicate the storage area,each variable should be given a unique name (identifier).

Rules for naming variables:


• A variable name can only have alphabets, numbers and the underscore(_).
• A variable name cannot begin with a number.
• It is a preferred practice to begin variable names with a lowercase character.
• A variable name cannot be a keyword like (int). Int is a keyword used to denote integers.
• A variable name can start with an underscore.

Reference variables:
• Reference variable is an alternate name of already existing variable.
• It cannot be changed to refer another variable and should be initialized at the time of
declaration and cannot be NULL.
• The operator ‘&’ is used to declare reference variable.

Example:

9
#include<iostream>
using namespace std;
int main(){
int a = 8;
int& b = 9;
cout<<“The variable a: “<<a;
cout<<“\n The reference variable r : “<<b;
return 0;
}

10
CHAPTER-6
Data types:
• Data types are declaration for variables.
• This determines the data type and size of data associated with variables.

Example program for data types:


#include <iostream>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
Output:
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 8
Size of float : 4
11
Size of double : 8
Size of wchar_t : 4
CHAPTER-7

Operators:

• Operators are symbols that perform operations on variables and values.

• For example:-

+ is an operator used for addition.

- is an operator used for subtraction.

Types of operators:

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

• Arithmetic operators are used to perform arithmetic operations on variables and data.

operator operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo operation(reminder after


division)

12
Example Program:

#include <iostream>
using namespace std;
int main() {
int a, b;
a = 7;
b = 2;
cout << "a + b = " << (a + b) << endl;
cout << "a - b = " << (a - b) << endl;
cout << "a * b = " << (a * b) << endl;
cout << "a / b = " << (a / b) << endl;
cout << "a % b = " << (a % b) << endl;
return 0;
}

Output:

a+b=9
a-b=5
a * b = 14
a/b=3
a%b=1

13
Assignment operator:

• Assignment operators are used to assign values to the variables.

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

Example program for assignment operator:

#include<iostream>
using namespace std;
int main(){
int a,b;
a=2;
b=7;
cout<<“a = “<<a<<endl;
cout<<“b = “<<b<<endl;
Cout<<“\n After a+=b;”<<endl;
a += b;
cout<< “a = “ <<a<<endl;
return 0;
}

14
Output:

a=2
b=7
After a += b;
a=9

Relational operator:
• A relational operator is used to check the relationship between two operands.
Operator Meaning Example

== Is equal to 3 == 5 gives us false

!= Not equal to 3 != 5 gives us true

> Greater than 3 > 5 gives us false

< Lesser than 3 < 5 gives us true

>= Greater than or equal to 3 >= 5 gives us false

<= Lesser than or equal to 3 <= 5 gives us true

Example program for Relational operator:


#include <iostream>
using namespace std;
int main() {
int a, b;
a = 3; b = 5; bool result;
result = (a == b); // false
cout << "3 == 5 is " << result << endl;
result = (a != b); // true
cout << "3 != 5 is " << result << endl;
result = a > b; // false
cout << "3 > 5 is " << result << endl;
result = a < b; // true
cout << "3 < 5 is " << result << endl;
result = a >= b; // false
cout << "3 >= 5 is " << result << endl;
result = a <= b; // true
cout << "3 <= 5 is " << result << endl;

15
return 0;
}
Output:
3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1
Logical Operator:
• Logical operators are used to check whether an expression is true or false.
• If the expression is true, it returns 1 whereas if the expression is false, it returns 0.

Operator Meaning Example

&& Logical AND, expression1 && expression2


True only if all the operands
are true

|| Logicl OR. expression1 || expression2


True if at least one of the
operands is true.

! Logical NOT. !expression


True only if the operand is
false.

Example program for Logical Operator:

#include <iostream>
using namespace std;
int main() {
bool result;
result = (3 != 5) && (3 < 5); // true
cout << "(3 != 5) && (3 < 5) is " << result << endl;
result = (3 == 5) && (3 < 5); // false
cout << "(3 == 5) && (3 < 5) is " << result << endl;
result = (3 == 5) && (3 > 5); // false

16
cout << "(3 == 5) && (3 > 5) is " << result << endl;
result = (3 != 5) || (3 < 5); // true
cout << "(3 != 5) || (3 < 5) is " << result << endl;
result = (3 != 5) || (3 > 5); // true
cout << "(3 != 5) || (3 > 5) is " << result << endl;
result = (3 == 5) || (3 > 5); // false
cout << "(3 == 5) || (3 > 5) is " << result << endl;
result = !(5 == 2); // true
cout << "!(5 == 2) is " << result << endl;
result = !(5 == 5); // false
cout << "!(5 == 5) is " << result << endl;
return 0;
}

Output:

(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0

Bitwise Operator:
• Bitwise operators perform operations on integer data at the individual bit-level.
• These operations include testing, setting, or shifting the actual bits.
Operator Description

& Bitwise AND Operator

| Bitwise OR Operator

^ Bitwise XOR Operator

~ Bitwise Complement Operator

17
<< Bitwise Shift Left Operator

>> Bitwise Shift Right Operator

Example program for Bitwise Operator:

#include <iostream>
using namespace std;
int main() {
int a=12, b=25;
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"a & b = "<<(a&b) <<endl;
cout<<"a | b = "<<(a|b)<<endl;
cout<<"a ^ b = "<<(a^b)<<endl;
return 0;
}

Output:
a = 12
b = 25
a&b=8
a | b = 29
a ^ b = 21

Operator precedence in C++ Operator:

Operator Description Example

sizeof returns the size of data type sizeof(int); // 4

?: returns value based on the condition string result = (5 > 0) ? "even" :


"odd"; // "even"

& represents memory address of the operand &num; // address of num

. accesses members of struct variables or class s1.marks = 92;


objects

18
-> used with pointers to access the class or struct ptr->marks = 92;
variables

<< prints the output value cout << 5;

>> gets the input value cin >> num;

19
CHAPTER-8
Conditional statement:

if Statements:

Syntax:
if(condition){
//body of statement
}

• The if statement evaluate the condition inside the paranthesis().


• If the condition evaluates to true, the code inside the body of if is executed.
• If the condition evaluates to false, the code inside the body of if is skipped.

Example program for if statement:

#include <iostream>
using namespace std;
int main() {
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
return 0;

20
}
Output:

x is greater than y

Else statement:
• Use the else statement to specify a block of code to be executed if the condition is false.
Syntax:

if(condition)
{
//block of code if condition is true
Else
{
//block of code if condition is false
}

Example program for if-else statement:


#include <iostream>
using namespace std;
int main() {
int time = 20;
if (time < 18) {
cout << "Good day.";

21
} else {
cout << "Good evening.";
}
return 0;
}

Output:
Good evening.

Else if statement:
• Use else if statements to specify a new condition if the first condition is false.

Syntax:

if (condition1)
{
//statement block to be executed if condition1 is true
}
else if(condition 2)
{
//statement block to be executed if condition2 is true
}
else
{
//block of code to be executed if the condition2 is false
}

22
Example program for else if statement:

#include <iostream>
using namespace std;
int main() {
int time =11;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
return 0;
}

Output:
Good day.

Nested if else statement:


• Sometimes we need to use if statement inside another if statement. This is known as
nested if statement.
• This is a multiple layers of if statements.

23
Syntax:

If(condition1)
{
//statements
if(condition2)//inner if statement
{
//statements
}
}

Note:
• We can add else and else if statements to the inner if statement as required.
• The inner if statement can also be inserted the outer else or else if statements (if they
exist).
• We can nest multiple layers of if statements.

Example program:
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
if (num != 0)
{
if (num > 0)
{
cout << "The number is positive." << endl;
}
else {
cout << "The number is negative." << endl;
}
}
else {

24
cout << "The number is 0 and it is neither positive nor negative." << endl;
}
cout << "This line is always printed." << endl;
return 0;
}

Output :
Enter an integer: 5
The number is positive.
This line is always printed.

Switch statement:

• The switch statement allows us to execute a block of code among many alternatives.

Syntax:

Switch(expression){
Case constant1:
//code to be executed if
//expression is equal to constant1;
Break;
Case constant2:
//code to be executed if;
//expression is equal to constant2;
Break;
.
.
default:
//code to be executed if
//expression doesn’t match any constant;
}

25
Example program for Switch statement:

#include <iostream>
using namespace std;
int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper) {
case '+': cout << num1 << " + " << num2 << " = " << num1 + num2;break;
case '-': cout << num1 << " - " << num2 << " = " << num1 - num2; break;
case '*': cout << num1 << " * " << num2 << " = " << num1 * num2; break;
case '/': cout << num1 << " / " << num2 << " = " << num1 / num2; break;
default: // operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct"; break;
}
return 0;

26
}

Output:

Enter an operator (+, -, *, /):


+
Enter two numbers:
2
3
2+3=5
Enter an operator (+, -, *, /):
*
Enter two numbers:
5
8
5 * 8 = 40

Jump statements:

• Jump statements are implemented to change the flow of the program when particular
conditions are satisfied.
• It is used within a program to end or continue a loop or to pause the execution of a
function.
• C++ has four jump statements:
1. continue
2. break
3. return
4. goto.
Continue:
• Instead of terminating the loop, it performs the next iteration of the same loop but
ignoring the parts specified by the condition.
• Within the loop, it must be used in conjunction with a decision-making statement.
• This statement can be used within a for, while, or do-while loop.

27
Break:
• If the condition is met, the loop is terminated with the break command.
• When the condition is met, the loop is broken and the remainder of the loop is skipped,
unlike the continue statement.
• Break statements are used in conjunction with decision-making statements such as if, if-
else, or switch statements in a for loop, which can be a for loop, while loop, or do-while
loop.
• It causes the loop to stop executing future iterations.

Return:
• It removes control from the function. It is more powerful than a break.
• It is used to end the entire function after the function has completed or after a
condition has been met.
• Except for the void() function, every function contains a return statement that returns
some value.
• Although the void() function can also have a return statement to conclude the function's
execution.

Goto:
• This statement enables us to jump directly to the section of the program that is being
referenced.
• Each goto statement is connected with a label that directs them to the section of the
programme for which they are named.
• Label statements can be written anywhere in the program; no before or after goto
statements are required.
• This statement makes understanding the flow of the program difficult, hence it is
avoided in program.

28
CHAPTER-9
Iteration Statement

• Iteration statements are used to create loops in the program.


• In other words, it repeats the set of statements until the condition for termination is
satisfied.
• There are four types:
1. For loop
2. While loop
3. Do-while
4. Nested loop
For loop

• for loop is used to iterate a part of the program several times.


• If the number of iteration is fixed, it is recommended to use for loop than while or do-
while loops.
Syntax:

for(initialization; condition; incr/decr)


{
//code to be executed
}

29
Example program for loop:

#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++)
{
cout<<i <<"\n";
}
}

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

While Loop:
• while loop is used to iterate a part of the program several times.
• If the number of iteration is not fixed, it is recommended to use while loop than for
loop.
Syntax:

While(condition)

//statement

30
Example program for while loop:

#include <iostream>
using namespace std;
int main()
{
int i=1;
while(i<=10)
{
cout<<i <<"\n";
i++;
}
}

Output:

1
2
3
4
5
6
7
8
9
10

31
Do while loop:
• do-while loop is used to iterate a part of the program several times.
• If the number of iteration is not fixed and you must have to execute the loop at least
once, it is recommended to use do-while loop.
• do-while loop is executed at least once because condition is checked after loop body.
Syntax:

do{
//code to be executed
}while(condition);

32
Example program for Do While loop:

#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
}

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

33
CHAPTER-10
ARRAY:

Definition:

• An array is a variable that can store multiple values of the same type.

For example:

➢ Suppose a class has 30 students, and we need to store the grades of all of them.
Instead of creating 30separate variables, we can simply create an array:
double grade[30];

ARRAY DECLARATION:

Syntax:
datatype arrayName[arraySize];

For example:

Access elements in array:


• Each element in an array is associated with a number.
• The number is known as an array index.
• We can access elements of an array by using those indices.
Syntax:
array[index];

34
ARRAY INITIALIZATION:

Syntax:

int x[6]={19,10,8,17,9,15};

Example program for displaying array elements:

#include <iostream>
using namespace std;
int main() {
int numbers[5] = {7, 5, 6, 12, 35};
cout << "The numbers are: ";
for (const int &n : numbers)
{
cout << n << " ";
}
cout << "\nThe numbers are: ";
for (int i = 0; i < 5; ++i)
{
cout << numbers[i] << " ";
}

35
return 0;
}
Output:
The numbers are: 7 5 6 12 35
The numbers are: 7 5 6 12 35
Advantages of Array:

• Code Optimization (less code)


• Random Access
• Easy to traverse data
• Easy to manipulate data
• Easy to sort data etc.

Disadvantage:
• Fixed size

Types of Array:

1. Single Dimensional (or) 1D Array


2. Multidimensional (or) 2D Array

1D Array or single dimensional Array:

• One dimensional array are the simplest form of an array in C++ language.
• We can easily declare, initialize, and manipulate a one-dimensional array.
• A one-dimensional array can be a parameter for function and so on.
• We can treat individual array element like any other C++ variables.

1-D Array Declaration:

• The syntax to declare a one-dimensional array is very simple.


<datatype><arrayname> [n];
• The two square brackets hold the number of elements in the array denoted by n.

Example:

float demo[10];

36
1-D Array Initialization:

• There are different ways to initialize an array.


• We must provide values to each array element before using them in your program.

Syntax:

<datatype><arrayname>[n] = {arrayvalue , array_value2 , ... , array_value n-1}

Example program for 1D array:

#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 0, 20, 0, 30};
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}

Output:

10
0
20
0
30

37
PASSING ARRAY TO AN FUNCTION:

• The size of the one-dimensional array is large and it is difficult to pass an entire array as
a function parameter.
• This will crash the memory or slow down the program.
• However, arrays are different than normal variables, they are like pointers, a variable
that refers to another variable instead of holding value.
• Only some characteristics of pointers are adopted by arrays.

Syntax:
functionname(arrayname);

Example program for Passing Array to a Function: Print Array Elements:

#include <iostream>
using namespace std;
void printArray(int arr[5]);
int main()
{
int arr1[5] = { 10, 20, 30, 40, 50 };
int arr2[5] = { 5, 15, 25, 35, 45 };
printArray(arr1); //passing array to function
printArray(arr2);
}
void printArray(int arr[5])
{
cout << "Printing array elements:"<< endl;
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}

OUTPUT:
Printing array elements:
10
20

38
30
40
50
Printing array elements:
5
15
25
35
45

MULTIDIMENSIONAL ARRAY:

• The multidimensional array is also known as rectangular arrays in C++.


• It can be two dimensional or three dimensional. The data is stored in tabular form (row
∗ column) which is also known as matrix.

Example program for Multidimensional Array:


#include <iostream>
using namespace std;
int main()
{
int test[3][3];
test[0][0]=5; test[0][1]=10; test[1][1]=15;
test[1][2]=20; test[2][0]=30; test[2][2]=10;
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{

39
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}

Output:
5 10 0
0 15 20
30 0 10

40
CHAPTER-11
Strings and String function
String:
• A string is an object of a class that represents sequence of characters.

Declaration of String:

• There are two ways to declare a String.

Type-1: Through an array of characters.


Example: char greeting[6];

Type-2: Through pointers


Example: char *greeting;

STRING INITIALIZATION:
Example:
char greeting[6]= {‘c’, ’l’, ’o’, ’u’, ’d’, ’\0’};
(or)
char greeting[]=“cloud”;
Output:

c l o u d \0

EXAMPLE PROGRAM FOR STRINGS:

#include <iostream>
using namespace std;
int main( ) {
string s1 = "Welcome";
char ch[] = { 'A', 'M', 'Y', 'P', 'O'};
string s2 = string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
Output:
Welcome
41
CODER
STRING MANIPULATION:

• strcpy(str1, str2): Copies string str2 into string str1.


• strcat(str1, str2): Concatenates string str2 onto the end of string str1.
• strlen(str1): Returns the length of string str1.
• strcmp(str1, str2): Returns 0 if str1 and str2 are the same; less than 0 if str1<str2;
greater than 0 if str1>str2.
• strchr(str1, ch): Returns a pointer to the first occurrence of character ch in string str1.
• strstr(str1, str2): Returns a pointer to the first occurrence of string str2 in string str1.

IMPORTANT FUNCTION:

1. append(): This function appends a part of a string to another string.


2. assign():This function assigns a partial string.
3. at(): This function obtains the character stored at a specified location.
4. begin(): This function returns a reference to the start of the string.
5. capacity(): This function gives the total element that can be stored.
6. compare(): This function compares a string against the invoking string.
7. empty(): This function returns true if the string is empty.
8. end(): This function returns a reference to the end of the string.
9. erase(): This function removes characters as specified.
10. find(): This function searches for the occurrence of a specified substring.
11. length(): It gives the size of a string or the number of elements of a string.
12. swap(): This function swaps the given string with the invoking one.

EXAMPLE PROGRAM FOR STRING FUNCTION:

#include <iostream>
#include <cstring>
using namespace std;
int main () {
char str1[10] = “welcome";
char str2[10] = "CODER";
char str3[10]; int len ;
strcpy( str3, str1);

42
cout << "strcpy( str3, str1) : " << str3 << endl;
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
return 0;
}

OUTPUT:
strcpy( str3, str1) : welcome
strcat( str1, str2): welcomeCODER
strlen(str1) : 12

Character String Function:

• C++ provides several functions that allow you to test and manipulate character data.
• The function prototypes are found in the header file name .
• Remember to add the line #include in program that use these functions.
• The table below lists and describes the character functions. Each function expects one
integer argument - the ASCII value of the character to be tested.
• Each function returns a non-zero value (true) if the condition tested is true and 0 (false)
if the condition tested is false.

43
C++ Functions Description

isalpha(character) Returns a nonzero number if the character is a letter ('A' - 'Z', 'a' -'z');
otherwise it returns zero.

isalnum(character) Returns a nonzero number if the character is a letter ('A' - 'Z', 'a' -'z', or '0' -
'9'; otherwise it returns zero.

isdigit(character) Returns a nonzero number if the character is digit (0 through 9);otherwise it


returns a zero.

isspace(character) Returns a nonzero number if the character is a whitespace (tab, space,


newline); otherwise it returns a zero.

isupper(character) Returns a nonzero number if the character is uppercase; otherwise it


returns a zero.

islower(character) Returns a nonzero number if the character is lowercase; otherwise it


returns a zero.

toupper(character) Return the uppercase equivalent if the character is lowercase; otherwise it


returns the character unchanged.

tolower(character) Return the lowercase equivalent if the character is uppercase; otherwise it


returns the character unchanged.

atoi(string) Converts an ASCII string to an integer (include # in your program)

atof(string) Converts an ASCII string to an float (include # in your program)

44
CHAPTER-12
FUNCTIONS
DEFINITION:

• A function is a block of code that performs a specific task.


• Suppose we need to create a program to create a circle and color it. We can create two
functions to solve this problem:
• a function to draw the circle
• a function to color the circle
• Dividing a complex problem into smaller chunks makes our program easy to understand
and reusable.
• There are two types of function:

1. Standard Library Functions: Predefined in C++.


2. User-defined Function: Created by users.

USER DEFINED FUNCTION:

• A user-defined function groups code to perform a specific task and that group of code is
given a name (identifier).
• The function is invoked from any part of the program, it all executes the codes defined
in the body of the function.
FUNCTION DECLARATION:

Syntax:
returnType functionName(parameter1,parameter2,….)
{
//function body
}

Example:

//function declaration
Void greet() //greet is a function name
{
Cout<<”Hello World”;
}

45
Calling a Function:
• We have declared a function named greet().
• To use the greet() function, we need to call it.
Example:
#include<iostream>
void greet()
{
//code
}

int main()
{
….
greet();
…..
}

Example program Displaying a text using function calling:

#include <iostream>
using namespace std;

// declaring a function
void greet() {
cout << "Hello there!";
}

int main() {

// calling the function


greet();

return 0;

46
}

Output:
Hello there!

FUNCTION PARAMETER:
• A function can be declared with parameters (arguments). A parameter is a value that is
passed when declaring a function.

Example :

void printNum(int num)


{
cout<<num;
}

Example program for function parameters:

#include <iostream>
using namespace std;
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {

int num1 = 5;
double num2 = 5.5;
displayNum(num1, num2);
return 0;
}

Output:

The int number is 5


The double number is 5.5

47
Call by value and call by reference:

• There are two ways to pass value or data to function.

Call by value:
• In call by value original value is not modified.
• Value being passed to the function is locally stored by the function parameter in stack
memory location.
• If you change the value of function parameter, it is changed for the current function
only.
• It will not change the value of variable inside the caller method such as main().

Example program:

#include <iostream>
using namespace std;
void change(int data);

48
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}

Output:

Value of the data is: 3

Call by reference:
• In call by reference, original value is modified because we pass reference (address).
• Address of the value is passed in the function, so actual and formal arguments share the
same address space.
• Hence, value changed inside the function, is reflected inside as well as outside the
function.

Example program:

#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function

49
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}

Output:

Value of x is: 100


Value of y is: 500

Inline function:

• 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 eliminate the cost of calls to small functions C++ proposes a new feature called inline
function.
• An inline function is a function that is expanded inline when it is invoked. That is the
compiler replaces the function call with the corresponding function code.

The inline function are defined as follows:

inline function-header
{
Function body;
}

Example:

inline double cube(double a)


{
return(a*a*a)
}

The above inline function can be invoked by statements like


c=cube(3.0);

50
d=cube(2.5+1.5);

• remember that the inline keyword merely sends a request, not a command to the
compliler.
• The compiler may ignore this request if the function definition is too long or too
complicated and compile the function as a normal function. Some of the situations
where inline expansion may not work are:
1. For functions returning values if a loop, a switch or a go to exists.
2. for function s not returning values, if a return statement exists.
3. if functions contain static variables.
4. if inline functions are recursive,.

Example:

#include<iostream>
inline float mul(float x, float y)
{
return(x*y);
}
inline double div(double p.double q)
{r
eturn(p/q);
}
main( )
{
float a=12.345;
float b=9.82;
cout<<mul(a,b)<<endl;
cout<<div(a,b)<<endl;
}

Output:

121.227898
1.257128

DEFAULT ARGUMENT: -

51
• C++ allows us to call a function without specifying all its arguments.
• In such cases, the function assigns a default value to the parameter which does not have
a matching argument in the function call.
• Default values are specified when the function is declared .
• The compiler looks at the prototype to see how many arguments a function uses and
alerts the program for possible default values.
Example: float amount (float principle, int period, float rate=0.15);
• The default value is specified in a manner syntactically similar to a variable initialization.
• The above prototype declares a default value of 0.15 to the argument rate.
• A subsequent function call like value=amount (5000,7); //one argument missing passes
the value of 5000 to principle and 7 to period and then lets the function, use default
value of 0.15 for rate.
• The call: - value=amount (5000,5,0.12); //no missing argument passes an explicite value
of 0.12 rate.
• One important point to note is that only the trailing arguments can have default values.
• That is, we must add default from right to left. We cannot provide a default to a
particular argument in the middle of an argument list.
Example: -
int mul(int i, int j=5,int k=10);//illegal
int mul(int i=0,int j,int k=10);//illegal
int mul(int i=5,int j);//illegal
int mul(int i=2,int j=5,int k=10);//illegal

• Default arguments are useful in situation whose some arguments always have the some
value.

Example:
#include <iostream>
using namespace std;

// A function with default arguments,


// it can be called with

// 2 arguments or 3 arguments or 4 arguments.

int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0

{
return (x + y + z + w);
}

52
int main()
{
// Statement 1
cout << sum(10, 15) << endl;
// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Output:
25
50
80
Function overloading:
• Two functions can have the same name if the number and/or type of arguments passed
is different.
• These functions having the same name but different arguments are known as
overloaded functions.

Example program for function overloading using different types of parameters:

#include <iostream>
using namespace std;
// function with float type parameter
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}
// function with int type parameter
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}
int main () {
// call function with int type parameter

53
cout << "Absolute value of -5 = " << absolute(-5) << endl;
cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}

Output:

Absolute value of -5 = 5

Absolute value of 5.5 = 5.5

Recursive function:

• When function is called inside the same function is known as recursive function.
• The function which calls the same function is known as recursive function.
• Function that calls itself and does not perform any task after function call is known as
tail recursion function.
• In tail recursion we generally call the same with written statement.

Syntax:

recursion function()

recursion function()

Advantages of Recursion:

• It makes our code shorter and cleaner.


• Recursion is required in problems concerning data structures and advanced algorithms,
such as Graph and Tree Traversal.

54
Disadvantages of Recursion:
• It takes a lot of stack space compared to an iterative program.
• It uses more processor time.
• It can be more difficult to debug compared to an equivalent iterative program.

Example program for Factorial of a number using Recursion:

// Factorial of n = 1*2*3*...*n

#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n, result;
cout << "Enter a non-negative number: ";
cin >> n;

result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Output:

Enter a non-negative number: 5

Factorial of 5 = 120

55
CHAPTER-13

Pointers

Definition:

• Pointers are variables that store the memory addresses of other variables.

Syntax:

int *pointVar;

Example program for pointers:

#include <iostream>

using namespace std;

int main() {

int var = 5;

// declare pointer variable

int* pointVar;

// store address of var

pointVar = &var;

56
// print value of var

cout << "var = " << var << endl;

// print address of var

cout << "Address of var (&var) = " << &var << endl

<< endl;

// print pointer pointVar

cout << "pointVar = " << pointVar << endl;

// print the content of the address pointVar points to

cout << "Content of the address pointed to by pointVar (*pointVar) = " << *pointVar << endl;

return 0;

Output:

var = 5

Address of var (&var) = 0x7ffe95804e3c

pointVar = 0x7ffe95804e3c

Content of the address pointed to by pointVar (*pointVar) = 5

Pointers and Array:

Pointers are variables that hold addresses of other variables. Not only can a pointer store the
address of a single variable, it can also store the address of cells of an array.

Syntax:

int *ptr;

int arr[5];

//store the address of first

57
//element of arr in ptr.

ptr = arr;

Example program for Pointers and Array:

// C++ Program to display address of each element of an array

#include <iostream>
using namespace std;

int main()
{
float arr[3];

// declare pointer variable


float *ptr;

cout << "Displaying address using arrays: " << endl;

// use for loop to print addresses of all array elements


for (int i = 0; i < 3; ++i)
{

58
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}

// ptr = &arr[0]
ptr = arr;
cout<<"\nDisplaying address using pointers: "<< endl;
// use for loop to print addresses of all array elements
// using pointer notation
for (int i = 0; i < 3; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}

return 0;
}

Output:

Displaying address using arrays:

&arr[0] = 0x7fffbfd0be0c

&arr[1] = 0x7fffbfd0be10

&arr[2] = 0x7fffbfd0be14

Displaying address using pointers:

ptr + 0 = 0x7fffbfd0be0c

ptr + 1 = 0x7fffbfd0be10

ptr + 2 = 0x7fffbfd0be14

POINTERS AND FUNCTIONS:

Passing pointers to functions in C++:

C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter
as a pointer type.

59
Example program:
#include <iostream>
#include <ctime>
using namespace std;
void getSeconds(unsigned long *par);

int main () {
unsigned long sec;
getSeconds( &sec );
// print the actual value
cout << "Number of seconds :" << sec << endl;
return 0;
}
void getSeconds(unsigned long *par) {
// get the current number of seconds
*par = time( NULL );
return;
}

Output:

Number of seconds :1672241157

• In this example where we pass an unsigned long pointer to a function and change the
value inside the function which reflects back in the calling function.
• The function which can accept a pointer, can also accept an array .

Example program:

#include <iostream>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);

int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};

60
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
}
double getAverage(int *arr, int size) {
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = double(sum) / size;
return avg;
}

Output:
Average value is: 214.4

Passing reference without pointers:


#include <iostream>
using namespace std;

// function definition to swap values


void swap(int &n1, int &n2) {
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{

61
// initialize variables
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
// call function to swap numbers
swap(a, b);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

Output:
Before swapping
a=1
b=2

After swapping
a=2
b=1

Passing by reference using pointers:

#include <iostream>
using namespace std;

// function prototype with pointer as parameters


void swap(int*, int*);
int main()
{
// initialize variables
int a = 1, b = 2;

62
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
// call function by passing variable addresses
swap(&a, &b);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
// function definition to swap numbers
void swap(int* n1, int* n2) {
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}

Output:
Before swapping
a=1
b=2

After swapping
a=2
b=1

Memory management:

• C++ allows us to allocate the memory of a variable or an array in run time. This is known
as dynamic memory allocation.
• In other programming languages such as Java and Python, the compiler automatically
manages the memories allocated to variables. But this is not the case in C++.

• In C++, we need to deallocate the dynamically allocated memory manually after we


have no use for the variable.

63
• We can allocate and then deallocate memory dynamically using
the new and delete operators respectively.

New operator:

• The new operator allocates memory to a variables.

Example:

/ declare an int pointer

int* pointVar;

// dynamically allocate memory

// using the new keyword

pointVar = new int;

// assign value to allocated memory

*pointVar = 45;

Here, we have dynamically allocated memory for an int variable using the new operator.

Notice that we have used the pointer pointVar to allocate the memory dynamically. This is
because the new operator returns the address of the memory location.

In the case of an array, the new operator returns the address of the first element of the array.

Syntax:

pointerVariable=new datatype;

Delete Operator:

Once we no longer need to use a variable that we have declared dynamically, we can deallocate
the memory occupied by the variable.

64
For this, the delete operator is used. It returns the memory to the operating system. This is
known as memory deallocation.

Syntax:

delete pointerVariable;

Example:

// declare an int pointer

int* pointVar;

// dynamically allocate memory

// for an int variable

pointVar = new int;

// assign value to the variable memory

*pointVar = 45;

// print the value stored in memory

cout << *pointVar; // Output: 45

// deallocate the memory

delete pointVar;

Example program for dynamic memory allocation:

#include <iostream>
using namespace std;
int main() {
// declare an int pointer
int* pointInt;

// declare a float pointer


float* pointFloat;

// dynamically allocate memory


pointInt = new int;
pointFloat = new float;

65
// assigning value to the memory
*pointInt = 45;
*pointFloat = 45.45f;
cout << *pointInt << endl;
cout << *pointFloat << endl;
// deallocate the memory
delete pointInt;
delete pointFloat;
return 0;
}
Output:

45

45.45

New and delete operators for Array:

Example program:

#include <iostream>
using namespace std;

int main() {

int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr;

// memory allocation of num number of floats


ptr = new float[num];

cout << "Enter GPA of students." << endl;


for (int i = 0; i < num; ++i) {
cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i);
}

66
cout << "\nDisplaying GPA of students." << endl;
for (int i = 0; i < num; ++i) {
cout << "Student" << i + 1 << ": " << *(ptr + i) << endl;
}
// ptr memory is released
delete[] ptr;

return 0;
}

Output:
Enter total number of students: 4
Enter GPA of students.
Student1: 3.6
Student2: 3.1
Student3: 3.9
Student4: 2.9

Displaying GPA of students.


Student1: 3.6
Student2: 3.1
Student3: 3.9
Student4: 2.9

67
CHAPTER-14
STRUCTURES AND UNION
STRUCTURES:

• The structure is a user-defined data type that is available in C++.


• Structures are used to combine different types of data types, just like an array is used to
combine the same type of data types.
• A structure is declared by using the keyword “struct“. When we declare a variable of the
structure we need to write the keyword “struct in C language but for C++ the keyword is
not mandatory

Syntax:

Struct
{
//declaration of struct
}

Example program for structure:

#include <iostream>
using namespace std;

struct CODER {
int A1;
char A2;
float A3;
};
int main()
{
struct CODER amy;
amy.A1 = 85;
amy.A2 = 'G';
amy.A3 = 989.45;
cout << "The value is : "
<< amy.A1 << endl;
cout << "The value is : "

68
<< amy.A2 << endl;
cout << "The value is : "
<< amy.A3 << endl;

return 0;
}

Output:
The value is : 85
The value is : G
The value is : 989.45

Struct using typedef:

typedef:

The typedef is used to give data type a new name to any existing data-type.

Example program:

#include <iostream>
using namespace std;

typedef struct CoderTech {

int A1;
char A2;
float A3;

} AT;
int main()
{
AT amy;
amy.A1 = 85;
amy.A2 = ‘A’;
amy.A3 = 989.45;

cout << "The value is : "

69
<< amy.A1 << endl;

cout << "The value is : "


<< amy.A2 << endl;

cout << "The value is : "


<< amy.A3 << endl;

return 0;
}
Output:
The value is : 85
The value is : A
The value is : 989.45

Unions:
• A union is a type of structure that can be used where the amount of memory used is a
key factor.
• Similarly, to the structure, the union can contain different types of data types.
• Each time a new variable is initialized from the union it overwrites the previous in C
language but in C++ we also don’t need this keyword and uses that memory location.
• This is most useful when the type of data being passed through functions is unknown,
using a union which contains all possible data types can remedy this problem.
• It is declared by using the keyword “union“.

Example program:

#include <iostream>
using namespace std;

union AT {
int Coder1;
char Coder2;
float Coder3;
};
int main()
{
union AT Coder1;

70
A1.Coder1 = 34;
cout << "The first value at "
<< "the allocated memory : " << A1.Coder1 << endl;
A1.Coder2 = 34;
cout << "The next value stored "
<< "after removing the "
<< "previous value : " << A1.Coder2 << endl;
A1.Coder3 = 34.34;
cout << "The Final value value "
<< "at the same allocated "
<< "memory space : " << A1.Coder3 << endl;
return 0;
}

Output:

The first value at the allocated memory : 34


The next value stored after removing the previous value : "
The Final value value at the same allocated memory space : 34.34

71
CHAPTER-15
CLASSES AND OBJECTS
Classes:

• A class is a blueprint of an object.

Create a class:

• Your class has a sketch (prototypes) of objects. Class is defined using class keyword
followed by the name of the class.
• The body of the class is defined inside the curly braces and terminated by a semi colon
at the end.

Syntax:

class className{

//Data

//Functions

};

Example:

class Room {

public:

double length;

double breadth;

double height;

72
double calculateArea(){

return length * breadth;

double calculateVolume(){

return length * breadth * height;

};

Objects:

• A class is defined only the specification for the object is defined no memory storage
allocated.
• To use the data and access functions defined in the class we need to create objects.

Syntax:

className object variableName;

• we can create objects of a class in any function of the program.


• we can create objects of a class within the class itself or in the other classes.
• We can create as many objects we want from a single class.

Access data members and member functions:

Access the data members and member functions of a class by using . (dot) operator.

Example:

Room2.calculateArea();

In this calculate area function inside the room class for object room 2.

That data members

Room.length = 5.5;

Example program for Objects and Class:

#include <iostream>
using namespace std;

73
// create a class
class Room {

public:
double length;
double breadth;
double height;

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;

// assign values to data members


room1.length = 32.5;
room1.breadth = 30.8;
room1.height = 11.2;

// calculate and display the area and volume of the room


cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}

Output:
Area of Room = 1001
Volume of Room = 11211.2

74
Public keyword:

It is the members or public and can be accessed anywhere from the program.

Private keyword:

The private member of a class can be accessed from within the class.

Example program using public and private class:

#include <iostream>
using namespace std;

class Room {
private:
double length;
double breadth;
double height;

public:

// function to initialize private variables


void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;

75
// pass the values of private variables as arguments
room1.initData(42.5, 30.8, 19.2);

cout << "Area of Room = " << room1.calculateArea() << endl;


cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}

Output:
Area of Room = 1309
Volume of Room = 25132.8

CHAPTER-16
ENCAPSULATION
Definition:
• Encapsulation is the process of wrapping similar code in one place.
• Encapsulation is one of the key features of object-oriented programming.
• It involves the bundling of data members and functions inside a single class.
Example:
class Rectangle {
public:
int length;
int breadth;

int getArea() {
return length * breadth;
}
};

76
Example program for Encapsulation:
// Program to calculate the area of a rectangle
#include <iostream>
using namespace std;

class Rectangle {
public:
int length;
int breadth;

Rectangle(int len, int brth) : length(len), breadth(brth) {}

int getArea() {
return length * breadth;
}
};

int main() {
Rectangle rect(8, 6);

77
cout << "Area = " << rect.getArea();

return 0;
}

Output:
Area = 48

Why Encapsulation?
• Encapsulation helps us keep related data and functions together, which makes our code
cleaner and easy to read.
• It helps to control the modification of our data members.
Example:
class Rectangle {
private:
int age;
public:
void setLength(int len) {
if (len >= 0)
length = len;
}
};

• The getter and setter functions provide read-only or write-only access to our class
members.

Example:
getLength() // provides read-only access
setLength() // provides write-only access

• It helps to decouple components of a system.


• These decoupled components (bundles) can be developed, tested, and debugged
independently and concurrently.

78
• And any changes in a particular component do not have any effect on other
components.

Data Hiding:
• Data hiding is a way of restricting the access of our data members by hiding the
implementation details.
• Encapsulation also provides a way for data hiding.
• We can use access modifiers to achieve data hiding in C++.

Example program for data hiding using access modifiers:


#include <iostream>
using namespace std;

class Rectangle {
private:

// Variables required for area calculation


int length;
int breadth;
public:
// Setter function for length
void setLength(int len) {
length = len;
}
// Setter function for breadth
void setBreadth(int brth) {
breadth = brth;
}

// Getter function for length


int getLength() {
return length;
}
// Getter function for breadth
int getBreadth() {
return breadth;
}
// Function to calculate area

79
int getArea() {
return length * breadth;
}
};
int main() {
// Create object of Rectangle class
Rectangle rectangle1;
// Initialize length using Setter function
rectangle1.setLength(8);
// Initialize breadth using Setter function
rectangle1.setBreadth(6);
// Access length using Getter function
cout << "Length = " << rectangle1.getLength() << endl;
// Access breadth using Getter function
cout << "Breadth = " << rectangle1.getBreadth() << endl;
// Call getArea() function
cout << "Area = " << rectangle1.getArea();
return 0;
}

Output:
Length = 8
Breadth = 6
Area = 48

CHAPTER-17
CONSTRUCTORS

Definition:
• A constructor is a special type of member function that is called automatically when an
object is created.
• A constructor has the same name as that of the class and it does not have a return type.
Example:

class Wall {
public:
// create a constructor

80
Wall() {
// code
}
};

Default constructors:
• A constructor with no parameters is known as a default constructor.

Example program for default constructor:


// C++ program to demonstrate the use of default constructor

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;

public:
// default constructor to initialize variable
Wall() {
length = 5.5;
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};

int main() {
Wall wall1;
return 0;
}

Output:
Creating a Wall
Length = 5.5

81
Note: If we have not defined a constructor in our class, then the C++ compiler will automatically
create a default constructor with an empty code and no parameters.

Parameterized constructor:
• A constructor with parameters is known as a parameterized constructor.
• This is the preferred method to initialize member data.

Example program for parameterized constructor:

#include <iostream>
using namespace std;

// declare a class
class Wall {

private:
double length;
double height;

public:
// parameterized constructor to initialize variables
Wall(double len, double hgt) {
length = len;
height = hgt;
}
double calculateArea() {
return length * height;
}
};

int main() {
// create object and initialize data members
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;


cout << "Area of Wall 2: " << wall2.calculateArea();

82
return 0;
}

Output:

Area of Wall 1: 90.3


Area of Wall 2: 53.55

Copy constructor:
• The copy constructor in C++ is used to copy data of one object to another.

Example program for copy constructor:

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;

public:

// initialize variables with parameterized constructor


Wall(double len, double hgt) {
length = len;
height = hgt;
}

// copy constructor with a Wall object as parameter


// copies data of the obj parameter
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}

double calculateArea() {

83
return length * height;
}
};

int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);

// copy contents of wall1 to wall2


Wall wall2 = wall1;

// print areas of wall1 and wall2


cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;
}

Output:

Area of Wall 1: 90.3


Area of Wall 2: 90.3

Note: A constructor is primarily used to initialize objects. They are also used to run a default
code when an object is created.

Shallow copying:
• In shallow copy, an object is created by simply copying the data of all variables of the
original object.
• This works well if none of the variables of the object are defined in the heap section of
memory.
• If some variables are dynamically allocated memory from heap section, then the copied
object variable will also reference the same memory location.
• This will create ambiguity and run-time errors, dangling pointer.
• Since both objects will reference to the same memory location, then change made by
one will reflect those change in another object as well. Since we wanted to create a
replica of the object, this purpose will not be filled by Shallow copy.

84
Example program:

// C++ program for the above approach


#include <iostream>
using namespace std;

// Box Class
class box {
private:
int length;
int breadth;
int height;

public:
// Function that sets the dimensions
void set_dimensions(int length1, int breadth1,
int height1)
{
length = length1;
breadth = breadth1;
height = height1;
}

// Function to display the dimensions


// of the Box object
void show_data()
{
cout << " Length = " << length
<< "\n Breadth = " << breadth
<< "\n Height = " << height
<< endl;
}
};

// Driver Code
int main()
{
// Object of class Box

85
box B1, B3;

// Set dimensions of Box B1


B1.set_dimensions(14, 12, 16);
B1.show_data();

// When copying the data of object


// at the time of initialization
// then copy is made through
// COPY CONSTRUCTOR
box B2 = B1;
B2.show_data();

// When copying the data of object


// after initialization then the
// copy is done through DEFAULT
// ASSIGNMENT OPERATOR
B3 = B1;
B3.show_data();

return 0;
}

Output:
Length = 14
Breadth = 12
Height = 16
Length = 14
Breadth = 12
Height = 16
Length = 14
Breadth = 12
Height = 16

86
Deep copying:

• In Deep copy, an object is created by copying data of all variables, and it also allocates
similar memory resources with the same value to the object.
• In order to perform Deep copy, we need to explicitly define the copy constructor and
assign dynamic memory as well, if required.
• Also, it is required to dynamically allocate memory to the variables in the other
constructors, as well.

Example program:
// C++ program to implement the
// deep copy
#include <iostream>
using namespace std;
// Box Class
class box {
private:
int length;
int* breadth;
int height;
public:
// Constructor
box()
{
breadth = new int;
}
// Function to set the dimensions
// of the Box
void set_dimension(int len, int brea,
int heig)
{
length = len;
*breadth = brea;
height = heig;
}

// Function to show the dimensions


// of the Box

87
void show_data()
{
cout << " Length = " << length
<< "\n Breadth = " << *breadth
<< "\n Height = " << height
<< endl;
}
// Parameterized Constructors for
// for implementing deep copy
box(box& sample)
{
length = sample.length;
breadth = new int;
*breadth = *(sample.breadth);
height = sample.height;
}

// Destructors
~box()
{
delete breadth;
}
};

int main()
{
box first;
first.set_dimension(12, 14, 16);
first.show_data();
box second = first;
second.show_data();
return 0;
}
Output:
Length = 12
Breadth = 14
Height = 16
Length = 12

88
Breadth = 14
Height = 16

Destructors:

• A destructor works opposite to constructor; it destructs the objects of classes. It can be


defined only once in a class. Like constructors, it is invoked automatically.

• A destructor is defined like constructor. It must have same name as class. But it is
prefixed with a tilde sign (~).

• C++ destructor cannot have parameters. Moreover, modifiers can't be applied on


destructors.

Example program for Constructor and destructor:

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}

Output:

Constructor Invoked
Constructor Invoked

89
Destructor Invoked
Destructor Invoked

Constructor overloading:
• It is similar as function overloading.
• The overloaded constructor or the same name(name of the class) are the different
number of arguments
• Depending upon the number and type of arguments passed with the corresponding
constructor is called.

Example program for constructor overloading:


// C++ program to demonstrate constructor overloading
#include <iostream>
using namespace std;

class Person {
private:
int age;
public:
// 1. Constructor with no arguments
Person() {
age = 20;
}
// 2. Constructor with an argument
Person(int a) {
age = a;
}
int getAge() {
return age;
}
};
int main() {
Person person1, person2(45);
cout << "Person1 Age = " << person1.getAge() << endl;
cout << "Person2 Age = " << person2.getAge() << endl;

90
return 0;
}

Output:
Person1 Age = 20
Person2 Age = 45

CHAPTER-18
INHERITANCE

Definition:
• Inheritance is one of the key features of Object-oriented programming in C++.
• It allows us to create a new class (derived class) from an existing class (base class).
• The derived class inherits the features from the base class and can have additional
features of its own.
Example:
class Animal {
// eat() function
// sleep() function
};

class Dog : public Animal {


// bark() function
};

91
is-a Relationship:
Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is present
between the two classes.
For example-
1. A car is a vehicle.
2. Orange is a fruit.
3. A surgeon is a doctor.
4. A dog is an animal.
Example program for Inheritance:
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
};
// derived class
class Dog : public Animal {
public:
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
int main() {

92
// Create object of the Dog class
Dog dog1;

// Calling members of the base class


dog1.eat();
dog1.sleep();
// Calling member of the derived class
dog1.bark();
return 0;
}

Output:
I can eat!
I can sleep!
I can bark! Woof woof!!

Protected members:

• The access modifier protected is especially relevant when it comes to C++ inheritance.
• Like private members, protected members are inaccessible outside of the class.
However, they can be accessed by derived classes and friend classes/functions.
• We need protected members if we want to hide the data of a class, but still want that
data to be inherited by its derived classes.\

Example program for Protected members:

#include <iostream>
#include <string>
using namespace std;

// base class
class Animal {

private:
string color;

protected:
string type;

93
public:
void eat() {
cout << "I can eat!" << endl;
}

void sleep() {
cout << "I can sleep!" << endl;
}

void setColor(string clr) {


color = clr;
}

string getColor() {
return color;
}
};

// derived class
class Dog : public Animal {

public:
void setType(string tp) {
type = tp;
}

void displayInfo(string c) {
cout << "I am a " << type << endl;
cout << "My color is " << c << endl;
}

void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
int main() {
// Create object of the Dog class
Dog dog1;

94
// Calling members of the base class
dog1.eat();
dog1.sleep();
dog1.setColor("black");

// Calling member of the derived class


dog1.bark();
dog1.setType("mammal");
// Using getColor() of dog1 as argument
// getColor() returns string data
dog1.displayInfo(dog1.getColor());

return 0;
}

Output:

I can eat!
I can sleep!
I can bark! Woof woof!!
I am a mammal
My color is black

Access modes in Inheritance:

There are three types of access specifiers in Inheritance.


1. Public
2. Private
3. Protected

Example:

class Animal {
// code
};

class Dog : private Animal {


// code

95
};

class Cat : protected Animal {


// code
};

1. public: If a derived class is declared in public mode, then the members of the base class
are inherited by the derived class just as they are.
2. private: In this case, all the members of the base class become private members in the
derived class.
3. protected: The public members of the base class become protected members in the
derived class.

Function overriding:
• As we know, inheritance is a feature of OOP that allows us to create derived classes
from a base class. The derived classes inherit features of the base class.
• Suppose, the same function is defined in both the derived class and the based class.
Now if we call this function using the object of the derived class, the function of the
derived class is executed.
• This is known as function overriding in C++. The function in derived class overrides the
function in base class.
Example program for function Overriding:
#include <iostream>
using namespace std;

class Base {
public:
void print() {
cout << "Base Function" << endl;

96
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}
Output:
Derived Function
Access overridden function:
• To access the overridden function of the base class, we use the scope resolution
operator (::).
• We can also access the overridden function by using a pointer of the base class to point
to an object of the derived class and then calling the function from that pointer.
Example program for access overridden function to the Base Class:
#include <iostream>
using namespace std;

class Base {
public:
void print() {
cout << "Base Function" << endl;
}

97
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1, derived2;
derived1.print();
// access print() function of the Base class
derived2.Base::print();
return 0;
}
Output:
Derived Function
Base Function
Call overridden function from derived class:
#include <iostream>
using namespace std;

class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {

98
public:
void print() {
cout << "Derived Function" << endl;

// call overridden function


Base::print();
}
};

int main() {
Derived derived1;
derived1.print();
return 0;
}

Output:
Derived Function
Base Function

Call overridden function using pointer:


#include <iostream>
using namespace std;

class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};

99
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;

// pointer of Base type that points to derived1


Base* ptr = &derived1;

// call function of Base class using ptr


ptr->print();
return 0;
}

Output:
Base Function

MULTILEVEL INHERITANCE:
• In C++ programming, not only we can derive a class from the base class but you can also
derive a class from the derived class. This form of inheritance is known as multilevel
inheritance.
Example:
class A {
... .. ...
};

100
class B: public A {
... .. ...
};
class C: public B {
... ... ...
};

Example program for multilevel inheritance:

#include <iostream>
using namespace std;

class A {
public:
void display() {
cout<<"Base class content.";
}
};

class B : public A {};

class C : public B {};


int main() {
C obj;
obj.display();
return 0;
}
Output:
Base class content.

MULTIPLE INHERITANCE:
• A class can be derived from more than one parent.
• For example, A class Bat is derived from base classes Mammal and Winged Animal. It
makes sense because bat is a mammal as well as a winged animal.

101
Example program for multiple inheritance:
#include <iostream>
using namespace std;
class Mammal {
public:
Mammal() {
cout << "Mammals can give direct birth." << endl;
}
};

class WingedAnimal {
public:
WingedAnimal() {
cout << "Winged animal can flap." << endl;
}
};

class Bat: public Mammal, public WingedAnimal {};

int main() {
Bat b1;
return 0;

102
}

Output:
Mammals can give direct birth.
Winged animal can flap.

FRIEND FUNCTION:
• A friend function can access the private and protected data of a class.
• We declare a friend function using the friend keyword inside the body of the class.
Syntax:
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}

Example program:

#include <iostream>
using namespace std;

class Distance {
private:
int meter;

// friend function
friend int addFive(Distance);

public:
Distance() : meter(0) {}

};

// friend function definition


int addFive(Distance d) {

//accessing private members from the friend function


d.meter += 5;
return d.meter;

103
}

int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;
}

Output:
Distance: 5

Friend class:
We can also use a friend Class in C++ using the friend keyword.

Example program:

#include <iostream>
using namespace std;

// forward declaration
class ClassB;

class ClassA {
private:
int numA;

// friend class declaration


friend class ClassB;

public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}
};

class ClassB {
private:
int numB;

public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}

// member function to add numA


// from ClassA and numB from ClassB

104
int add() {
ClassA objectA;
return objectA.numA + numB;
}
};

int main() {
ClassB objectB;
cout << "Sum: " << objectB.add();
return 0;
}

Output:

Sum: 13

VIRTUAL FUNCTIONS:

• A virtual function is a member function in the base class that we expect to redefine in
derived classes.
• A virtual function is used in the base class in order to ensure that the function is
overridden.
• This especially applies to cases where a pointer of base class points to an object of a
derived class.
Syntax:
class Base {
public:
void print() {
// code
}
};

class Derived : public Base {


public:
void print() {
// code
}
};

Example program:
#include <iostream>
using namespace std;

105
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;

// pointer of Base type that points to derived1


Base* base1 = &derived1;

// calls member function of Derived class


base1->print();

return 0;
}

Output:

Derived Function

Example program for Virtual function demonstration:


// C++ program to demonstrate the use of virtual function

#include <iostream>
#include <string>
using namespace std;

class Animal {
private:
string type;

public:
// constructor to initialize type

106
Animal() : type("Animal") {}

// declare virtual function


virtual string getType() {
return type;
}
};

class Dog : public Animal {


private:
string type;

public:
// constructor to initialize type
Dog() : type("Dog") {}

string getType() override {


return type;
}
};

class Cat : public Animal {


private:
string type;

public:
// constructor to initialize type
Cat() : type("Cat") {}

string getType() override {


return type;
}
};

void print(Animal* ani) {


cout << "Animal: " << ani->getType() << endl;
}

int main() {
Animal* animal1 = new Animal();
Animal* dog1 = new Dog();
Animal* cat1 = new Cat();

print(animal1);

107
print(dog1);
print(cat1);

return 0;
}

Output:

Animal: Animal
Animal: Dog
Animal: Cat

CLASS TEMPLATES:

• There are two ways we can implement templates:

1. Function Templates
2. Class Templates
• Similar to function templates, we can use class templates to create a single class to work
with different data types.

• Class templates come in handy as they can make our code shorter and more
manageable.

Class Template Declaration:


• A class template starts with the keyword template followed by template parameter(s)
inside <> which is followed by the class declaration.
Example:
template <class T>
class className {
private:
T var;
... .. ...
public:
T functionName(T arg);
... .. ...
};

Creating a class Template Object:

108
• Once we've declared and defined a class template, we can create its objects in other
classes or functions (such as the main() function)
Syntax:
className<dataType> classObject;

Example program for Class Templates:

#include <iostream>
using namespace std;

// Class template
template <class T>
class Number {
private:
// Variable of type T
T num;

public:
Number(T n) : num(n) {} // constructor

T getNum() {
return num;
}
};

int main() {

// create object with int type


Number<int> numberInt(7);

// create object with double type


Number<double> numberDouble(7.7);

cout << "int Number = " << numberInt.getNum() << endl;


cout << "double Number = " << numberDouble.getNum() << endl;

return 0;
}

Output:

109
int Number = 7
double Number = 7.7

Example Simple calculator program using Class Template:


#include <iostream>
using namespace std;

template <class T>


class Calculator {
private:
T num1, num2;

public:
Calculator(T n1, T n2) {
num1 = n1;
num2 = n2;
}

void displayResult() {
cout << "Numbers: " << num1 << " and " << num2 << "." << endl;
cout << num1 << " + " << num2 << " = " << add() << endl;
cout << num1 << " - " << num2 << " = " << subtract() << endl;
cout << num1 << " * " << num2 << " = " << multiply() << endl;
cout << num1 << " / " << num2 << " = " << divide() << endl;
}

T add() { return num1 + num2; }


T subtract() { return num1 - num2; }
T multiply() { return num1 * num2; }
T divide() { return num1 / num2; }
};

int main() {
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);

110
cout << "Int results:" << endl;
intCalc.displayResult();

cout << endl


<< "Float results:" << endl;
floatCalc.displayResult();

return 0;
}

Output:

Int results:
Numbers: 2 and 1.
2+1=3
2-1=1
2*1=2
2/1=2

Float results:
Numbers: 2.4 and 1.2.
2.4 + 1.2 = 3.6
2.4 - 1.2 = 1.2
2.4 * 1.2 = 2.88
2.4 / 1.2 = 2

Class templates with Multiple Parameters:


• we can use multiple template parameters and even use default arguments for those
parameters.
Example:

template <class T, class U, class V = int>


class ClassName {
private:
T member1;
U member2;
V member3;
... .. ...
public:

111
... .. ...
};

Example program for class template with multiple parameter:

#include <iostream>
using namespace std;

// Class template with multiple and default parameters


template <class T, class U, class V = char>
class ClassTemplate {
private:
T var1;
U var2;
V var3;

public:
ClassTemplate(T v1, U v2, V v3) : var1(v1), var2(v2), var3(v3) {} // constructor

void printVar() {
cout << "var1 = " << var1 << endl;
cout << "var2 = " << var2 << endl;
cout << "var3 = " << var3 << endl;
}
};

int main() {
// create object with int, double and char types
ClassTemplate<int, double> obj1(7, 7.7, 'c');
cout << "obj1 values: " << endl;
obj1.printVar();

// create object with int, double and bool types


ClassTemplate<double, char, bool> obj2(8.8, 'a', false);
cout << "\nobj2 values: " << endl;
obj2.printVar();

return 0;
}

Output:

obj1 values:
var1 = 7

112
var2 = 7.7
var3 = c

obj2 values:
var1 = 8.8
var2 = a
var3 = 0

113
CHAPTER-19
POLYMORPHISM

Definition:

• Polymorphism is an important concept of object-oriented programming.


• It simply means more than one form.
• That is, the same entity (function or operator) behaves differently in different scenarios.

Why polymorphism?

• Polymorphism allows us to create consistent code.


For example,

• Suppose we need to calculate the area of a circle and a square. To do so, we can create
a Shape class and derive two classes Circle and Square from it.

• In this case, it makes sense to create a function having the same name calculateArea() in
both the derived classes rather than creating functions with different names, thus
making our code more consistent.

• There are four ways to implement polymorphism:

1. Function overloading
2. Operator overloading
3. Function overloading
4. Virtual function

Function overloading:
• we can use two functions having the same name if they have different parameters
(either types or number of arguments).

• And, depending upon the number/type of arguments, different functions are called.

Example program:

#include <iostream>
using namespace std;

// Function with 2 int parameters


int sum(int num1, int num2) {
return num1 + num2;
114
}

// Function with 2 double parameters


double sum(double num1, double num2) {
return num1 + num2;
}

// Function with 3 int parameters


int sum(int num1, int num2, int num3) {
return num1 + num2 + num3;
}

int main() {
// Call function with 2 int parameters
cout << "Sum 1 = " << sum(5, 6) << endl;

// Call function with 2 double parameters


cout << "Sum 2 = " << sum(5.5, 6.6) << endl;

// Call function with 3 int parameters


cout << "Sum 3 = " << sum(5, 6, 7) << endl;

return 0;
}

Output:

Sum 1 = 11
Sum 2 = 12.1
Sum 3 = 18

Operator overloading:

• we can overload an operator as long as we are operating on user-defined types like


objects or structures.

• We cannot use operator overloading for basic types such as int, double, etc.

• Operator overloading is basically function overloading, where different operator


functions have the same symbol but different operands.

• And, depending on the operands, different operator functions are executed.

115
Example program:

#include <iostream>
using namespace std;

class Count {
private:
int value;

public:

// Constructor to initialize count to 5


Count() : value(5) {}

// Overload ++ when used as prefix


void operator ++() {
value = value + 1;
}

void display() {
cout << "Count: " << value << endl;
}
};

int main() {
Count count1;

// Call the "void operator ++()" function


++count1;

count1.display();
return 0;
}

Output:

Count: 6

Function overloading:
• We can have the same function in the base class as well as its derived classes.

• When we call the function using an object of the derived class, the function of the
derived class is executed instead of the one in the base class.

116
• So, different functions are executed depending on the object calling the function.

• This is known as function overriding.

Example program:

#include <iostream>
using namespace std;

class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;

// Call print() function of Derived class


derived1.print();

return 0;
}

Output:

Derived Function

117
Virtual functions:

• We may not be able to override functions if we use a pointer of the base class to point
to an object of the derived class.

• Using virtual functions in the base class ensures that the function can be overridden in
these cases.

• Virtual functions actually fall under function overriding.


Example program:

#include <iostream>
using namespace std;

class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;

// pointer of Base type that points to derived1


Base* base1 = &derived1;

// calls member function of Derived class


base1->print();

return 0;
}

Output:

Derived Function

118
Pure virtual Function:

• Pure virtual functions are used,

• If a function doesn't have any use in the base class


• But the function must be implemented by all its derived classes

• A pure virtual function doesn't have the function body and it must end with = 0.

Example program for Pure virtual function:

#include <iostream>
using namespace std;
class car //base or super or parent
{
public:
virtual void speed()=0;//pure virtual function
};
class BMW: public car{
public:
void speed() {
cout<<"200 km/hr\n";
}
};
class Audi: public car{
public:
void speed() {
cout<<"250 km/hr";
}
};
int main()
{
BMW b;
Audi a;
b.speed();
a.speed();
return 0;
}

Output:

200 km/hr
250 km/hr

119
CHAPTER-20

ABSTRACT CLASS
Definition:

• An abstract class is a class that is declared with an abstract keyword which is a restricted
class hence cannot be used to create objects; however, they can be subclassed.
• To access abstract class, it must be inherited from another class. In class
implementation and inheritance, when we want to define the same functions both in
the base and derived class, we use the keyword ‘virtual’ along with the base class
function.
• This ‘virtual’ function specifies that the same function is redefined or overridden in the
derived class.
• Therefore, an abstract class is a class with a pure virtual function.

Example program for abstract class with pure virtual function:

#include <iostream>
using namespace std;

// Abstract class
class Shape {
protected:
float dimension;

public:
void getDimension() {
cin >> dimension;
}

// pure virtual Function


virtual float calculateArea() = 0;
};

// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
}
};

// Derived class
120
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
}
};

int main() {
Square square;
Circle circle;

cout << "Enter the length of the square: ";


square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;

cout << "\nEnter radius of the circle: ";


circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;

return 0;
}

Output:

Enter the length of the square: 4


Area of square: 16

Enter radius of the circle: 5


Area of circle: 78.5

121
CHAPTER-21
EXCEPTION AND FILE HANDLING
Exception Handling:

• 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 whilea program
is running, such as an attempt to divide by zero.Exceptions provide a way to transfer
control from one part of a program to another.
• C++ exception handling is built upon three keywords:
1. Try
2. Catch
3. throw.
throw: A program throws an exception when a problem shows up. Thisis done using a throw
keyword.
catch: A program catches an exception with an exception handler at the place in a program
where
you want to handle the problem. The catch keyword indicates the catching of an exception.
try: A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.
• Assuming a block will raise an exception, a method catches an exception usinga
combination of the try and catch keywords.
• A try/catch block is placed around the code that might generate an exception.
• Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch lookslike the following:
try
{
// protected code

122
}
catch( ExceptionName e1 )
{
// catch block
}
catch( ExceptionName e2 )
{
// catch block
}
catch( ExceptionName eN )
{
// catch block
}

You can list down multiple catch statements to catch different type of exceptions in case
your try block raises more than one exception in different situations.
ThrowingExceptions: Exceptions can be thrown anywhere within a code block using
throw statements.
The operand of the throw statements determines a type for the exception and can be
any expression and the type of the result of the expression determines the type of
exception thrown.
Following is an example of throwing an exception when dividing by zero condition
occurs:
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}

123
return (a/b);
}
Catching Exceptions:
• The catch block following the try block catches any exception.
• You can specify what type of exception you want to catch and this is determined by the
exception declaration that appears in parentheses following the keyword catch.

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

• Above code will catch an exception of ExceptionName type.


• If you want to specify that a catch block should handle any type of exception that is
thrownin a try block, you must put an ellipsis, ..., between the parentheses enclosing the
exception declaration as follows:
• The following is an example, which throws a division by zero exception and wecatch it in
catch block.
Example program:

#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}

124
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
5
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}

Output:
Division by zero condition!

C++StandardExceptions:
• C++ provides a list of standard exceptions defined in <exception> which we can use in
our programs.
• These are arranged in a parent-child class hierarchy shown below:

Exception Description

std::exception An exception and parent class of all the standard C++ exceptions.
std::bad_alloc This can be thrown by new.
std::bad_cast This can be thrown by dynamic_cast.
std::bad_exception This is useful device to handle unexpected exceptions in a C++
program
std::bad_typeid This can be thrown by typeid.
std::logic_error An exception that theoretically can be detected by reading thecode.
std::domain_error This is an exception thrown when a mathematically invalid domainis
used

125
std::invalid_argument This is thrown due to invalid arguments.
std::length_error This is thrown when a too big std::string is created
std::out_of_range This can be thrown by the at method from for example a std::vectorand
std::bitset<>::operator[]().
std::runtime_error An exception that theoretically can not be detected by reading thecode.
std::overflow_error This is thrown if a mathematical overflow occurs.
std::range_error This is occured when you try to store a value which is out of range.
std::underflow_error This is thrown if a mathematical underflow occurs

Define New Exceptions:


You can define your own exceptions by inheriting and overriding exception class functionality.
Following is the example, which shows how you can use std::exception class to implement your
own exception in standard way.
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception
{
const char * what () const throw ()
{
return "C++ Exception";
}
};
int main()
{
try
{
throw MyException();

126
}
catch(MyException& e)
{
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
DefineNewExceptions:
You can define your own exceptions by inheriting and overriding exception class functionality.
Following
is the example, which shows how you can use std::exception class to implement your own
exception in
standard way:
10
MyException caught
C++ Exception
This would produce the following result:
Here, what() is a public method provided by exception class and it has been overridden by all
the child
exception classes. This returns the cause of an exception.
}
catch(std::exception& e)
{
//Other errors
}
}

Output:
MyException caught
C++ Exception

127
FILES AND STREAM:
• C++ provides the following classes to perform output and input of characters to/from
files:
1. ofstream: Stream class to write on files
2. ifstream: Stream class to read from files
3. fstream: Stream class to both read and write from/to files.
• These classes are derived directly or indirectly from the classes istream, and ostream.
• We have already used objects whose types were these classes: cin is an object of class
istream and cout is an object of class ostream.
• Therfore, we have already been using classes that are related to our file streams.
• And in fact, we can use our file streams the same way we are already used to use cin
and cout, with the only difference that we have to associate these streams with physical
files.

Let's see an example:


// basic file operations
#include <iostream.h>
#include <fstream.h>
int main ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
• This code creates a file called example.txt and inserts a sentence into it in the same way
we are used to do with cout, but using the file stream myfile instead.

128
Open a file
• The first operation generally performed on an object of one of these classes is to associate
it
• to a real file.
• This procedure is known as to open a file.
• An open file is represented within a program by a stream object (an instantiation of one
of these classes, in the previous example this was myfile) and any input or output
operation performed on this stream object will be applied to the physical file associated
to it.
• In order to open a file with a stream object we use its member function open():
• open (filename, mode);
• Where filename is a null-terminated character sequence of type const char * (the same
type that string literals have) representing the name of the file to be opened, and mod e
is an optional parameter with a combination of the following flags:
1. ios::in Open for input operations.
2. ios::out Open for output operations.
3. ios::binary Open in binary mode.
4. ios::ate Set the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.
5. ios::app All output operations are performed at the end of the file,
appending the content to the current content of the file. This flag can only
be used in streams open for output-only operations.
6. ios::trunc If the file opened for output operations already existed before,
its previous content is deleted and replaced by the new one.
All these flags can be combined using the bitwise operator OR (|). For example, if we want to
open the file example.bin in binary mode to add data we could do it by the following call to
member function open():
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);

129
• Each one of the open() member functions of the classes ofstream, ifstream and fstream
has a default mode that is used if the file is opened without a second argument: class
default mode parameter
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
• For ifstream and ofstream classes, ios::in and ios::out are automatically and respectivelly
assumed, even if a mode that does not include them is passed as second argument to the
open() member function.
• The default value is only applied if the function is called without specifying any value for
the mode parameter. If the function is called with any value in that parameter the
default mode is overridden, not combined.
• File streams opened in binary mode, perform input and output operations
independently of any format considerations. Non-binary files are known as text files,
and some translations may occur due to formatting of some special characters (like
newline and carriage returncharacters).
• Since the first task that is performed on a file stream object is generally to open a file,
these three classes include a constructor that automatically calls the open() member
function and has the exact same parameters as this member.
• Therefor, we could also have declared the previous myfile object and conducted the
same opening operation in our previous example by writing:
ofstream myfile (“example.bin”, ios::out | ios::app | ios::binary);

• Combining object construction and stream opening in a single statement. Both forms to
open a file are valid and equivalent.
• To check if a file stream was successful opening a file, you can do it by calling to member
is_open() with no arguments. This member function returns a bool value of true in the
case that indeed the stream object is associated with an open file, or false otherwise:

130
if (myfile.is_open()) {
/* ok, proceed with output */
}
Closing a file
When we are finished with our input and output operations on a file we shall close it so that
its resources become available again.
In order to do that we have to call the stream's member function close(). This member function
takes no parameters, and what it does is to flush the associated buffers and close the file:
myfile.close();
• Once this member function is called, the stream object can be used to open another file,
and the file is available again to be opened by other processes.
• In case that an object is destructed while still associated with an open file, the
destructor
automatically calls the member function close().
Text files
• Text file streams are those where we do not include the ios::binary flag in their opening
mode.
• These files are designed to store text and thus all values that we input or output from/to
them can suffer some formatting transformations, which do not necessarily correspond to
their literal binary value.
• Data output operations on text files are performed in the same way we operated with
cout:
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())

131
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Output:
This is a line.
This is another line.
• Data input from a file can also be performed in the same way that we did with cin:
Example program:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}

132
else cout << "Unable to open file";
return 0;
}
Output:
This is a line.
This is another line.

• This last example reads a text file and prints out its content on the screen.
• Notice how we have used a new member function, called eof() that returns true in the
case that the end of the file has been reached.
• We have created a while loop that finishes when indeed myfile.eof() becomes true (i.e.,
the end of the file has been reached).

Checking state flags


• In addition to eof(), which checks if the end of file has been reached, other member
functions exist to check the state of a stream (all of them return a bool value):
bad()
• Returns true if a reading or writing operation fails. For example in the case that we try
to
write to a file that is not open for writing or if the device where we try to write has no space
left.
fail()
• Returns true in the same cases as bad(), but also in the case that a format error
happens, like when an alphabetical character is extracted when we are trying to read an
integer number.
eof()
• Returns true if a file open for reading has reached the end.
good()

133
• It is the most generic state flag: it returns false in the same cases in which calling any of
the previous functions would return true.
• In order to reset the state flags checked by any of these member functions we have just
seen we can use the member function clear(), which takes no parameters.
get and put stream pointers
• All i/o streams objects have, at least, one internal stream pointer:
o ifstream, like istream, has a pointer known as the get pointer that points to the
element to be read in the next input operation.
o ofstream, like ostream, has a pointer known as the put pointer that points to the
location where the next element has to be written.
o Finally, fstream, inherits both, the get and the put pointers, from iostream
(which is itself derived from both istream and ostream).
• These internal stream pointers that point to the reading or writing locations within a
stream
• can be manipulated using the following member functions:
tellg() and tellp()
• These two member functions have no parameters and return a value of the member
type
pos_type, which is an integer data type representing the current position of the get stream
pointer (in the case of tellg) or the put stream pointer (in the case of tellp).
seekg() and seekp()
• These functions allow us to change the position of the get and put stream pointers. Both
functions are overloaded with two different prototypes. The first prototype is:
seekg ( position );
seekp ( position );
• Using this prototype the stream pointer is changed to the absolute position position
(counting from the beginning of the file). The type for this parameter is the same as the
one returned by functions tellg and tellp: the member type pos_type, which is an
integer value.

134
• The other prototype for these functions is:
seekg ( offset, direction );
seekp ( offset, direction );
• Using this prototype, the position of the get or put pointer is set to an offset value
relative to some specific point determined by the parameter direction. offset is of the
member type off_type, which is also an integer type.
• And direction is of type seekdir, which is an enumerated type (enum) that determines
the point from where offset is counted from, and that can take any of the following
values:
o ios::beg offset counted from the beginning of the stream
o ios::cur offset counted from the current position of the stream pointer
o ios::end offset counted from the end of the stream
The following example uses the member functions we have just seen to obtain the size of a
file:
// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;
int main () {
long begin,end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}

135
Output:
size is: 40 bytes

136
CHAPTER-22
STL and Lambda
STL Containers:

o Containers can be described as the objects that hold the data of the same type. Containers
are used to implement different data structures for example arrays, list, trees, etc.
o Following are the containers that give the details of all the containers as well as the
header file and the type of iterator associated with them :

Container Description Header iterator


file

vector vector is a class that creates a dynamic array allowing <vector> Random
insertions and deletions at the back. access

list list is the sequence containers that allow the insertions <list> Bidirectional
and deletions from anywhere.

deque deque is the double ended queue that allows the <deque> Random
insertion and deletion from both the ends. access

set set is an associate container for storing unique sets. <set> Bidirectional

multiset Multiset is an associate container for storing non- <set> Bidirectional


unique sets.

map Map is an associate container for storing unique key- <map> Bidirectional
value pairs, i.e. each key is associated with only one
value(one to one mapping).

multimap multimap is an associate container for storing key- value <map> Bidirectional
pair, and each key can be associated with more than
one value.

stack It follows last in first out(LIFO). <stack> No iterator

queue It follows first in first out(FIFO). <queue> No iterator

137
Priority- First element out is always the highest priority element. <queue> No iterator
queue

Classification of containers :

o Sequence containers
o Associative containers
o Derived containers

Iterator:

o Iterators are pointer-like entities used to access the individual elements in a container.
o Iterators are moved sequentially from one element to another element. This process is
known as iterating through a container.

o Iterator contains mainly two function.

138
begin(): The member function begin() returns an iterator to the first element of the vector.
end(): The member function end() returns an iterator to the past-the-last element of a
container.

Iterator Categories:
Iterators are mainly divided into five categories:

1. Input iterator:
o An Input iterator is an iterator that allows the program to read the values from
the container.
o Dereferencing the input iterator allows us to read a value from the container, but
it does not alter the value.
o An Input iterator is a one way iterator.
o An Input iterator can be incremented, but it cannot be decremented.
2. Output iterator:

139
o An output iterator is similar to the input iterator, except that it allows the program
to modify a value of the container, but it does not allow to read it.
o It is a one-way iterator.
o It is a write only iterator.
3. Forward iterator:
o Forward iterator uses the ++ operator to navigate through the container.
o Forward iterator goes through each element of a container and one element at a
time.
4. Bidirectional iterator:

o A Bidirectional iterator is similar to the forward iterator, except that it also moves
in the backward direction.
o It is a two way iterator.
o It can be incremented as well as decremented.

5. Random Access Iterator:


o Random access iterator can be used to access the random element of a container.
o Random access iterator has all the features of a bidirectional iterator, and it also
has one more additional feature, i.e., pointer addition. By using the pointer
addition operation, we can access the random element of a container.

Operations supported by iterators:

iterator Element Read Write Increment Comparison


access operation

input -> v = *p ++ ==,!=

output *p = v ++

forward -> v = *p *p = v ++ ==,!=

Bidirectional -> v = *p *p = v ++,-- ==,!=

140
Random ->,[ ] v = *p *p = v ++,--,+,-,+=,--= ==,!=,<,>,<=,>=
access

Algorithms

Algorithms are the functions used across a variety of containers for processing its contents.

Points to Remember:

• Algorithms provide approx 60 algorithm functions to perform the complex operations.


• Standard algorithms allow us to work with two different types of the container at the
same time.
• Algorithms are not the member functions of a container, but they are the standalone
template functions.
• Algorithms save a lot of time and effort.
• If we want to access the STL algorithms, we must include the <algorithm> header file in
our program.

STL Algorithms:

• Nonmutating algorithms: Nonmutating algorithms are the algorithms that do not alter
any value of a container object nor do they change the order of the elements in which
they appear. These algorithms can be used for all the container objects, and they make
use of the forward iterators.
• Mutating algorithms: Mutating algorithms are the algorithms that can be used to alter
the value of a container. They can also be used to change the order of the elements in
which they appear.
• Sorting algorithms: Sorting algorithms are the modifying algorithms used to sort the
elements in a container.
• Set algorithms: Set algorithms are also known as sorted range algorithm. This algorithm
is used to perform some function on a container that greatly improves the efficiency of a
program.

141
• Relational algorithms: Relational algorithms are the algorithms used to work on the
numerical data. They are mainly designed to perform the mathematical operations to all
the elements in a container.

Function Objects:

• A Function object is a function wrapped in a class so that it looks like an object.


• A function object extends the characteristics of a regular function by using the feature of
aN object oriented such as generic programming.
• Therefore, we can say that the function object is a smart pointer that has many
advantages over the normal function.

Following are the advantages of function objects over a regular function:

o Function objects can have member functions as well as member attributes.


o Function objects can be initialized before their usage.
o Regular functions can have different types only when the signature differs.
Function objects can have different types even when the signature is the same.
o Function objects are faster than the regular function.

• A function object is also known as a 'functor'. A function object is an object that contains
atleast one definition of operator() function. It means that if we declare the object 'd' of
a class in which operator() function is defined, we can use the object 'd' as a regular
function.
• Suppose 'd' is an object of a class, operator() function can be called as:

d();

which is same as:

d.operator() ( );

142
Example program:
#include <iostream>
using namespace std;
class function_object
{
public:
int operator()(int a, int b)
{
return a+b;
}
};

int main()
{
function_object f;
int result = f(5,5);
cout<<"Addition of a and b is : "<<result;

return 0;
}
Output:
Addition of a and b is : 10

143
Lambda Expression:

• C++ STL includes useful generic functions like std::for_each. Unfortunately they can also
be quite cumbersome to use, particularly if the functor you would like to apply is unique
to the particular function.

• So this function that you'll create will be in that namespace just being used at that one
place. The solution to this is using anonymous functions.

• C++ has introduced lambda expressions in C++11 to allow creating anonymous function.

Example program:

#include<iostream>
#include<vector>
#include <algorithm> // for_each
using namespace std;

int main() {
vector<int> myvector;
myvector.push_back(1);
myvector.push_back(2);
myvector.push_back(3);

for_each(myvector.begin(), myvector.end(), [](int x) {


cout << x*x << endl;
});
}

Output:
1

144
4
9
The (int x) is used to define the arguments that the lambda expression would be called with.
The [] are used to pass variables from the local scope to the inner scope of the lambda, this is
called capturing variables. These expressions if simple, can auto deduce their types. You can
also explicitly provide type information using the following syntax
[](int x) -> double {
return x/2.0;
}

145

You might also like