c++ Material Vijitha (1)
c++ Material Vijitha (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.
1
DIFFERENCE BETWEEN C AND C++:
2
CHAPTER-2
REQUIREMENTS TO START C++:
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.
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.
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:
• To indicate the storage area,each variable should be given a unique name (identifier).
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.
Operators:
• For example:-
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
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:
= 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;
#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
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.
#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 OR Operator
17
<< Bitwise Shift Left 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
18
-> used with pointers to access the class or struct ptr->marks = 92;
variables
19
CHAPTER-8
Conditional statement:
if Statements:
Syntax:
if(condition){
//body of 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
}
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.
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:
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
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:
34
ARRAY INITIALIZATION:
Syntax:
int x[6]={19,10,8,17,9,15};
#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:
Disadvantage:
• Fixed size
Types of 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.
Example:
float demo[10];
36
1-D Array Initialization:
Syntax:
#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);
#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:
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:
STRING INITIALIZATION:
Example:
char greeting[6]= {‘c’, ’l’, ’o’, ’u’, ’d’, ’\0’};
(or)
char greeting[]=“cloud”;
Output:
c l o u d \0
#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:
IMPORTANT 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
• 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.
44
CHAPTER-12
FUNCTIONS
DEFINITION:
• 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();
…..
}
#include <iostream>
using namespace std;
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
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 :
#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:
47
Call by value and call by reference:
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:
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:
Inline function:
inline function-header
{
Function body;
}
Example:
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;
{
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.
#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
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:
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.
// 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:
Factorial of 5 = 120
55
CHAPTER-13
Pointers
Definition:
• Pointers are variables that store the memory addresses of other variables.
Syntax:
int *pointVar;
#include <iostream>
int main() {
int var = 5;
int* pointVar;
pointVar = &var;
56
// print value of var
cout << "Address of var (&var) = " << &var << endl
<< endl;
cout << "Content of the address pointed to by pointVar (*pointVar) = " << *pointVar << endl;
return 0;
Output:
var = 5
pointVar = 0x7ffe95804e3c
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];
57
//element of arr in ptr.
ptr = arr;
#include <iostream>
using namespace std;
int main()
{
float arr[3];
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:
&arr[0] = 0x7fffbfd0be0c
&arr[1] = 0x7fffbfd0be10
&arr[2] = 0x7fffbfd0be14
ptr + 0 = 0x7fffbfd0be0c
ptr + 1 = 0x7fffbfd0be10
ptr + 2 = 0x7fffbfd0be14
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:
• 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
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
#include <iostream>
using namespace std;
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++.
63
• We can allocate and then deallocate memory dynamically using
the new and delete operators respectively.
New operator:
Example:
int* pointVar;
*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:
int* pointVar;
*pointVar = 45;
delete pointVar;
#include <iostream>
using namespace std;
int main() {
// declare an int pointer
int* pointInt;
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
Example program:
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr;
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
67
CHAPTER-14
STRUCTURES AND UNION
STRUCTURES:
Syntax:
Struct
{
//declaration of struct
}
#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
typedef:
The typedef is used to give data type a new name to any existing data-type.
Example program:
#include <iostream>
using namespace std;
int A1;
char A2;
float A3;
} AT;
int main()
{
AT amy;
amy.A1 = 85;
amy.A2 = ‘A’;
amy.A3 = 989.45;
69
<< amy.A1 << 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:
71
CHAPTER-15
CLASSES AND OBJECTS
Classes:
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(){
double calculateVolume(){
};
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:
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.
Room.length = 5.5;
#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() {
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.
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
75
// pass the values of private variables as arguments
room1.initData(42.5, 30.8, 19.2);
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;
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
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++.
class Rectangle {
private:
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.
#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.
#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);
82
return 0;
}
Output:
Copy constructor:
• The copy constructor in C++ is used to copy data of one object to another.
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
double calculateArea() {
83
return length * height;
}
};
int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);
return 0;
}
Output:
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:
// 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;
}
// Driver Code
int main()
{
// Object of class Box
85
box B1, B3;
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;
}
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 is defined like constructor. It must have same name as class. But it is
prefixed with a tilde sign (~).
#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.
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
};
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;
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.\
#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;
}
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");
return 0;
}
Output:
I can eat!
I can sleep!
I can bark! Woof woof!!
I am a mammal
My color is black
Example:
class Animal {
// code
};
95
};
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;
}
};
98
public:
void print() {
cout << "Derived Function" << endl;
int main() {
Derived derived1;
derived1.print();
return 0;
}
Output:
Derived Function
Base Function
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;
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 {
... ... ...
};
#include <iostream>
using namespace std;
class A {
public:
void display() {
cout<<"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;
}
};
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) {}
};
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;
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) {}
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
}
};
Example program:
#include <iostream>
using namespace std;
105
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
return 0;
}
Output:
Derived Function
#include <iostream>
#include <string>
using namespace std;
class Animal {
private:
string type;
public:
// constructor to initialize type
106
Animal() : type("Animal") {}
public:
// constructor to initialize type
Dog() : type("Dog") {}
public:
// constructor to initialize type
Cat() : type("Cat") {}
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:
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.
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;
#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() {
return 0;
}
Output:
109
int Number = 7
double Number = 7.7
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;
}
int main() {
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
110
cout << "Int results:" << endl;
intCalc.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
111
... .. ...
};
#include <iostream>
using namespace std;
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();
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:
Why polymorphism?
• 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.
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;
int main() {
// Call function with 2 int parameters
cout << "Sum 1 = " << sum(5, 6) << endl;
return 0;
}
Output:
Sum 1 = 11
Sum 2 = 12.1
Sum 3 = 18
Operator overloading:
• We cannot use operator overloading for basic types such as int, double, etc.
115
Example program:
#include <iostream>
using namespace std;
class Count {
private:
int value;
public:
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count 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.
Example program:
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
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.
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
return 0;
}
Output:
Derived Function
118
Pure virtual Function:
• A pure virtual function doesn't have the function body and it must end with = 0.
#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.
#include <iostream>
using namespace std;
// Abstract class
class Shape {
protected:
float dimension;
public:
void getDimension() {
cin >> dimension;
}
// 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;
return 0;
}
Output:
121
CHAPTER-21
EXCEPTION AND FILE HANDLING
Exception Handling:
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
}
#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
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.
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).
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 :
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
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.
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.
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.
output *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:
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 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();
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);
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