0% found this document useful (0 votes)
3 views94 pages

OOPS

The document provides an overview of C++, a middle-level programming language developed by Bjarne Stroustrup, detailing its structure, tokens, and operators. It covers essential components such as the program structure, various types of operators (arithmetic, relational, logical, etc.), and control flow statements. Additionally, it explains basic input and output operations in C++, emphasizing the significance of the main function and the use of libraries for handling streams.

Uploaded by

sarvagya
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)
3 views94 pages

OOPS

The document provides an overview of C++, a middle-level programming language developed by Bjarne Stroustrup, detailing its structure, tokens, and operators. It covers essential components such as the program structure, various types of operators (arithmetic, relational, logical, etc.), and control flow statements. Additionally, it explains basic input and output operations in C++, emphasizing the significance of the main function and the use of libraries for handling streams.

Uploaded by

sarvagya
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/ 94

Notes Prepared By : Sarvagya Jain

Unit -I
Basics of C++: C++ is a middle-level programming language developed by Bjarne
Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as
Windows, Mac OS, and the various versions of UNIX.
C++ is an Object Oriented Programming language but is not purely Object Oriented. Its
features like Friend and Virtual, violate some of the very important OOPS features, rendering
this language unworthy of being called completely Object Oriented. Its a middle level
language.
Structure of C++ Program
The structure of the program written in C++ language is
as follows:
Documentation Section:
This section comes first and is used to document the
logic of the program that the programmer is going to
code.
It can also be used to write for the purpose of the
program.
Header Files:
a program includes various programming elements like
built-in functions, classes, keywords, constants, operators, etc. that are already defined in the
standard C++ library.In order to use such predefined elements in a program, an appropriate
header must be included in the program.
Namespaces:
A namespace permits grouping of various entities like classes, objects, functions, and various
C++ tokens, etc. under a single name.
Definition Section:
It is used to declare some constants and assign them some value. In this section, anyone can
define your own data type using primitive data types.
Global Declaration Section:
Here the variables and the class definitions which are going to be used in the program are
declared to make them global.
Function Declaration Section:
It contains all the functions which our main functions need.Usually, this section contains the
User-defined functions.
Main Function:
● The main function tells the compiler where to start the execution of the program.
The execution of the program starts with the main function.
C++ Tokens
A token is the smallest element of a program that is meaningful to the compiler. Tokens can
be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
Notes Prepared By : Sarvagya Jain
6. Operators
1.Keywords: Keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. C++ language supports 63
keywords.
2.Identifiers: Identifiers are used as the general terminology for the naming of variables,
functions and arrays. These are user-defined names consisting of an arbitrarily long sequence
of letters and digits with either a letter or the underscore(_) as a first character.
3.Constants: Constants are also like normal variables. But, the only difference is, their
values can not be modified by the program once they are defined. Constants refer to fixed
values. They are also called literals.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
4.Strings: Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in
double-quotes. Whereas, a character is enclosed in single quotes in C and C++.Declarations
for String:
● char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
● char string[20] = “geeksforgeeks”;
5.Special Symbols: The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose.[] () {}, ; * = #
6.Operators: Operators are symbols that trigger an action when applied to C variables and
other objects. The data items on which operators act upon are called operands.
Basic Input and Output in C++
C++ comes with libraries that provide us with many ways for performing input and output. In
C++ input and output are performed in the form of a sequence of bytes or more commonly
known as streams.
Input Stream: If the direction of flow of bytes is from the device(for example, Keyboard) to
the main memory then this process is called input.
std::cin(standard console input): reads the value from the console as per the type specified.
Syntax : cin>>Variable name;
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device( display screen ) then this process is called output.
std::cout(standard console input): reads the value from the console as per the type specified.
Syntax : cout<<Variable name;
Operators and Expressions
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of
operators −
Notes Prepared By : Sarvagya Jain

Increment and Decrement Operators


C programming has two operators increment ++ and decrement -- to change the value of an
operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These
two operators are unary operators, meaning they only operate on a single operand.
++ and -- operator as prefix and postfix
● If you use the ++ operator as a prefix like: ++var, the value of var is incremented by
1; then it returns the value.
● If you use the ++ operator as a postfix like: var++, the original value of var is returned
first; then var is incremented by 1.
Example: // Working of increment and decrement operators
#include <iostream>
using namespace std;
int main() {
int var1 = 5, var2 = 5;
cout<<var1++<<endl;
cout<<++var2<<endl;
return 0;
}
Output:
5
6
Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction,
multiplication, division etc on numerical values (constants and variables).
Notes Prepared By : Sarvagya Jain

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division (modulo division)

Example: // Working of arithmetic operators


#include <iostream>
using namespace std;
int main()
{
int a = 9,b = 4, c;
c = a+b;
cout<<c<<endl;
c = a-b;
cout<<c<<endl;
c = a*b;
cout<<c<<endl;
c = a/b;
cout<<c<<endl;
c = a%b;
cout<<”Remainder when a divided by b=”<<c<<endl;
return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
Relational Operators
A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.

Operator Meaning of Operator Example


Notes Prepared By : Sarvagya Jain

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0

Example: // Working of relational operators


#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 5, c = 10;
cout<<( a == b)<<endl;
cout<< (a == c)<<endl;
cout<< (a > b)<<endl;
cout<<( a > c)<<endl;
cout<<( a < b)<<endl;
cout<<"(a < c)<<endl;
cout<<(a != b)<<endl;
cout<<( a != c)<<endl;
cout<<(a >= b)<<endl;
cout<<(a >= c)<<endl;
cout<<(a <= b)<<endl;
cout<<(a <= c)<<endl;
return 0;
}
Output
1
0
0
0
0
1
0
1
1
0
1
Notes Prepared By : Sarvagya Jain
1
Logical Operators
An expression containing a logical operator returns either 0 or 1 depending upon whether the
expression results true or false. Logical operators are commonly used in decision making in C
programming.

Operator Meaning Example

Logical AND. True only if If c = 5 and d = 2 then, expression


all operands are true ((c==5) (d>5)) equals to 0.

|| Logical OR. True only if If c = 5 and d = 2 then, expression


either one operand is true ((c==5) || (d>5)) equals to 1.

! Logical NOT. True only if If c = 5 then, expression !(c==5) equals


the operand is 0 to 0.

Example 5:// Working of logical operators


#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) (c > b);
cout<<"\n(a == b) (c > b) is "<< result;
result = (a == b) (c < b);
cout<<"\n(a == b) (c < b) is "<< result;
result = (a == b) || (c < b);
cout<<"\n(a == b) || (c < b) is "<< result;
result = (a != b) || (c < b);
cout<<"\n(a != b) || (c < b) is " <<result;
result = !(a != b);
cout<<"\n!(a != b) is "<< result;
result = !(a == b);
cout<<"\n!(a == b) is "<< result;
return 0;
}
Output
(a == b) (c > b) is 1
(a == b) (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
Assignment Operators
Notes Prepared By : Sarvagya Jain
An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =

Operator Example Same as

= 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 3: // Working of assignment operators


#include <iostream>
using namespace std;
int main()
{
int a = 5, c;
c = a; // c is 5
coût<<"\n c ="<< c;
c += a; // c is 10
coût<<"\n c ="<< c;
c -= a; // c is 5
coût<<"\n c ="<< c;
c *= a; // c is 25
coût<<"\n c ="<< c;
c /= a; // c is 5
coût<<"\n c ="<< c;
c %= a; // c = 0
coût<<"\n c ="<< c;
return 0;
}
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
Bitwise Operators
Notes Prepared By : Sarvagya Jain
During computation, mathematical operations like: addition, subtraction, multiplication,
division, etc are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C++ programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

1. The (bitwise AND) : takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) : takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) : takes two numbers as operands and does XOR on every bit of
two numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift): takes two numbers, left shifts the bits of the first operand, the
second operand decides the number of places to shift.
5. The >> (right shift) :takes two numbers, right shifts the bits of the first operand, the
second operand decides the number of places to shift.
6. The ~ (bitwise NOT) : C or C++ takes one number and inverts all bits of it
Example:
// Program to demonstrate use of bitwise operators
#include <iostream>
using namespace std;
int main()
{
unsigned char a = 5, b = 9;
cout<<"\n a = , b = "<< a<< b;
cout<<"\n a&b = "<<(a&b);
cout<<"\n a|b = " <<(a | b);
cout<<"\n a^b = "<<( a ^ b);
coût<<"\n ~a =" <<(a = ~a);
cout<<"\n b<<1 ="<<( b << 1);
cout<<"\n b>>1 ="<<( b >> 1);
return 0;
Notes Prepared By : Sarvagya Jain
}
Output:
a = 5, b = 9
a&b=1
a|b = 13
a^b = 12
~a = 250
b<<1 = 18
b>>1 = 4
Ternary Operator
The ternary operator is used to execute code based on the result of a binary condition.
It takes in a binary condition as input, which makes it similar to an 'if-else' control flow
block. It also, however, returns a value, behaving similar to a function.
Syntax
result = binaryCondition ? value Returned If True : value Returned If False;
Example:
#include <iostream>
using namespace std;
int main()
{
int age;
cout<<"Enter your age";
cin>>age;
(age>=18)? cout<<"eligible for voting" : cout<<"not eligible for voting";
return 0;
}
Output:
Enter your Age 24;
You are eligible for voting;
Control Flow Statement.
Control statements control the flow of execution of the statements of a program. The various
types of control statements in C language are as under:-
● Conditional/Branching Statements.
● Looping / Iteration Statement.
● Jumping Statement
Conditional/Branching Statements.
These are the statements that execute a statement on the base of the condition. When the
condition matches, the statement is executed or else it is skipped. There are 4 types of
selection statements.
These are being explained in detail below.
If Statement
If the statement is a condition block. When the condition is true, all the statements given in
this block are executed. If the condition is not true, then no statement of this block is
executed. The general syntax
if(condition)
{
Notes Prepared By : Sarvagya Jain
//statements to be executed when condition is true.
}
Example:
// Program to display a number if it is negative
#include <iostream>
using namespace std;
int main()
{
int number;
cout<<"Enter an integer: ";
cin>> number;
// true if number is less than 0
if (number < 0) {
cout<<"\n You entered ."<< number;
}
return 0;
}
Output
Enter an integer: -2
You entered -2.
If-else Statement
The else block is also appended with the if statement in the if else statement. Else block
contains statements that will execute if the condition is false. Its general syntax is being given
below.
if(condition)
{
//Statements to be executed when condition is true.
}
else
{
//Statements to be executed when condition is false.
}
Example
// Check whether an integer is odd or even
#include <iostream>
using namespace std;
int main() {
int number;
cout<<"Enter an integer: ";
cin>> number;
// True if the remainder is 0
if (number%2 == 0) {
cout<<" is an even integer."<<number;
}
else {
cout<<" is an odd integer."<<number;
Notes Prepared By : Sarvagya Jain
}
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
if...else if Ladder
The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2
possibilities.
The if...else ladder allows you to check between multiple test expressions and execute
different statements.
Syntax
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
Example
// Program to relate two integers using =, > or < symbol
#include <iostream>
using namespace std;
int main() {
int number1, number2;
cout<<"Enter two integers: ";
cin>>number1>> number2;
//checks if the two integers are equal.
if(number1 == number2) {
cout<<"Result: "<<number1<<” = ”<<number2;
}
//checks if number1 is greater than number2.
else if (number1 > number2) {
cout<<"Result: " <<number1<<”>” <<number2;
}
//checks if both test expressions are false
else {
cout<<"Result: "<<number1<<”<”<< number2;
Notes Prepared By : Sarvagya Jain
}
return 0;
}
Output
Enter two integers: 12
23
Result: 12 < 23
Nested if...else
It is possible to include an if...else statement inside the body of another if...else statement.
Example
// Program to relate two integers using =, > or < symbol
#include <iostream>
using namespace std;
int main() {
int number1, number2;
cout<<"Enter two integers: \n";
cin>> number1>> number2;
if (number1 >= number2) {
if (number1 == number2) {
cout<<"Result: "<<number1<<” = ”<<number2;
}
else {
cout<<"Result: "<< number1<<”>”<< number2;
}
}
else {
cout<<"Result: "<<number1<<”<”<<number2;
}
return 0;
}
Enter two integers: 12
23
Result: 12 < 23
Switch ... case
The switch case statement is used when we have multiple options and we need to perform a
different task for each option.
Syntax:
switch (variable or an integer expression)
{
case constant:
//C++ Statements
;
case constant:
//C++ Statements
;
default:
Notes Prepared By : Sarvagya Jain
//C++ Statements
;
}
Example:
// the working of a switch case statement in C++ program.
#include <iostream>
using namespace std;
int main()
{
int num=2;
switch(num+2)
{
case 1:
cout<<"Case1: Value is: " <<num<<endl;
case 2:
cout<<"Case1: Value is: " <<num<<endl;
case 3:
cout<<"Case1: Value is: "<<num<<endl;
default:
cout<<"Default: Value is: "<< num<<endl;
}
return 0;
}
Output:
Default: value is: 4
Looping Statements:
Looping Statements in C execute the sequence of statements many times until the stated
condition becomes false. A loop in C consists of two parts, a body of a loop and a control
statement. The control statement is a combination of some conditions that direct the body of
the loop to execute until the specified condition becomes false.
‘C’ programming language provides us with three types of loop constructs:
1. The while loop
2. The do-while loop
3. The for loop
Sr. Loop Type Description
No.

1. While Loop In a while loop, a condition is evaluated before processing a body


of the loop. If a condition is true then and only then the body of a
loop is executed.

2. Do-While Loop In a do…while loop, the condition is always executed after the
body of a loop. It is also called an exit-controlled loop.
Notes Prepared By : Sarvagya Jain
3. For Loop In a for loop, the initial value is performed only once, then the
condition tests and compares the counter to a fixed value after each
iteration, stopping the for loop when false is returned.

For loop
A for loop is a more efficient loop structure in ‘C++’ programming. The general structure of
for loop syntax in C++ is as follows:
Syntax of For Loop:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
// Following program illustrates the for loop in C++ programming example:
#include<iostream>
using namespace std;
int main()
{
int number;
for(number=1;number<=10;number++) //for loop to print 1-10 numbers
{
cout<<"\n"<<number; //to print the number
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
While Loop :
A while loop is the most straightforward looping structure. While loop syntax in C++
programming language is as follows:
Syntax of While Loop in C++:
while (condition) {
statements;
}
Following program illustrates while loop in C++ programming example:
#include<iostream>
using namespace std;
#include<conio.h>
Notes Prepared By : Sarvagya Jain
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
cout<<"\n"<<num;
num++; //incrementing operation
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
Do-While loop:
A do…while loop in C++ is similar to the while loop except that the condition is always
executed after the body of a loop. It is also called an exit-controlled loop.
Syntax of do while loop in C++ programming language is as follows:
Syntax of Do-While Loop in C++:
do {
statements
} while (expression);

//Below is a do-while loop in C++ example to print a table of number 2:


#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
cout<<"\n"<<2*num;
num++; //incrementing operation
}while(num<=10);
return 0;
}
Output:
2
Notes Prepared By : Sarvagya Jain
4
6
8
10
12
14
16
18
20
Jumping Statement:
The C programming language allows jumping from one statement to another. It also supports
break, continue, return and go to jump statements.
break
● It is a keyword which is used to terminate the loop (or) exit from the block.
● The control jumps to the next statement after the loop (or) block.
● break is used with for, while, do-while and switch statement.
● When break is used in nested loops then, only the innermost loop is terminated.
The syntax for break statement is as follows −

Example
//Following is the C++ program for break statement −
#include<iostream>
using namespace std;
int main( ){
int i;
for (i=1; i<=5; i++){
cout<< i<<endl;
if (i==3)
break;
}
return 0;
}
Output
When the above program is executed, it produces the following output −
123
continue
The syntax for the continue statement is as follows −
Notes Prepared By : Sarvagya Jain

Example
//Following is the C++ program for the continue statement −
#include<iostream>
using namespace std;
int main( ){
int i;
for (i=1; i<=5; i++){
if (i==2)
continue;
cout<<"\n"<< i;
}
return 0;
}
Output
When the above program is executed, it produces the following output −
12345
goto
It is used after the normal sequence of program execution by transferring the control to some
other part of the program.
The syntax for the goto statement is as follows −

Example
//Following is the C++ program for the goto statement −
#include<iostream>
using namespace std;
int main( ) {
cout<<"Hello";
goto l1;
Notes Prepared By : Sarvagya Jain
cout<<"How are";
l1: cout<<"you";
return 0;
}
Output
When the above program is executed, it produces the following output −
Hello you

Function:
A function is a block of code that performs a specific task. Dividing a large program into the
basic building blocks known as function. The function contains the set of programming
statements enclosed by {}. A function can be called multiple times to provide reusability and
modularity to the program.
In other words, we can say that the collection of functions creates a program. The function is
also known as procedure or subroutine in other programming languages.
There are three aspects of a function.
1. Function declaration
return_type function_name (argument list);
2. Function call
function_name (argument_list)
3. Function definition
return_type function_name (argument list)
{
function body;
}
The syntax of creating function:
return_type function_name(data_type parameter...)
{
//code to be executed
}
Types of Functions
There are two types of functions in C programming:
Library Functions: are the functions which are declared in the header files such as gets(),
puts(), sqrt(), floor() etc.
User-defined functions: are the functions which are created by the programmer, so that he/she
can use it many times. It reduces the complexity of a big program and optimizes the code.
The syntax of creating function:
return_type function_name(data_type parameter...)
{
//code to be executed
}
A function may or may not accept any argument. It may or may not return any value. Based
on these facts, There are four different aspects of function calls.
● function without arguments and without return value
● function without arguments and with return value
● function with arguments and without return value
Notes Prepared By : Sarvagya Jain
● function with arguments and with return value
//Example for Function without argument and return value
#include<iostream>
using namespace std;
void sum();
void main()
{
cout<<"\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
cout<<"\n”<<Enter two numbers";
cin>>a>>b;
cout<<"The sum is "<<(a+b);
}
Output
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
//Example for Function without argument and with return value
// program to calculate the area of the square
#include<iostream>
using namespace std;
int sum();
void main()
{
cout<<"Going to calculate the area of the square\n";
float area = square();
cout<<"The area of the square:\n"<<area;
}
int square()
{
float side;
cout<<"Enter the length of the side in meters: ";
cin>>side;
return side * side;
}
Going to calculate the area of the square
Enter the length of the side in meters: 10
The area of the square: 100.000000
//Example for Function with argument and without return value
//program to calculate the average of five numbers.
#include<iostream>
Notes Prepared By : Sarvagya Jain
using namespace std;
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
cout<<"\nGoing to calculate the average of five numbers:";
cout<<"\nEnter five numbers:";
cin>>a>>b>>c>>d>>e;
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
cout<<"The average of given five numbers :"<<avg;
}
Going to calculate the average of five numbers:
Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000
//Example for Function with argument and with return value
//Program to check whether a number is even or odd
#include<iostream>
using namespace std;
int even_odd(int);
void main()
{
int n,flag=0;
cout<<"\nGoing to check whether a number is even or odd";
cout<<"\nEnter the number: ";
cin>>n;
flag = even_odd(n);
if(flag == 0)
{
cout<<"\nThe number is odd";
}
else
{
cout<<"\nThe number is even";
}
}
int even_odd(int n)
{
Notes Prepared By : Sarvagya Jain
if(n%2 == 0)
{
return 1;
}
else
{
return 0;
}
}
Going to check whether a number is even or odd
Enter the number: 100
The number is even
Passing value to function:
There are two methods to pass the data into the function in C language, i.e., call by value and
call by reference.
call by value and call by reference.
Call by value
● In the call by value method, the value of the actual parameters is copied into the
formal parameters. In other words, we can say that the value of the variable is used in
the function call in the call by value method.
● In the call by value method, we can not modify the value of the actual parameter by
the formal parameter.
● In call by value, different memory is allocated for actual and formal parameters since
the value of the actual parameter is copied into the formal parameter.
● The actual parameter is the argument which is used in the function call whereas the
formal parameter is the argument which is used in the function definition.
//Call by Value Example: Swapping the values of the two variables
#include <iostream>
using namespace std;
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
cout<<"\n Before swapping the values in main a = , b ="<<a<<” ”<<b;
swap(a,b);
cout<<"\n After swapping values in main a = , b ="<<a<<” ”<<b;
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
cout<<"\n After swapping values in function a = , b = "<<a<<” ”<<b;
}
Notes Prepared By : Sarvagya Jain
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference
● In call by reference, the address of the variable is passed into the function call as the
actual parameter.
● The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
● In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored
at the address of the actual parameters, and the modified value gets stored at the same
address.
//Call by reference Example: Swapping the values of the two variables
#include <iostream> using namespace std;
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
cout<<"\nBefore swapping the values in main a = , b = "<<a<<” ”<<b;
swap(a,b);
cout<<"\nAfter swapping values in main a = , b = \n"<<a<<” ”<<b;
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
cout<<"After swapping values in function a = , b = \n"*a,*b);
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference.

No. Call by value Call by reference

1 A copy of the value is passed into the An address of value is passed into the
function function
Notes Prepared By : Sarvagya Jain

2 Changes made inside the function are Changes made inside the function validate
limited to the function only. The values outside of the function also. The values of
of the actual parameters do not change the actual parameters do change by
by changing the formal parameters. changing the formal parameters.

3 Actual and formal arguments are created Actual and formal arguments are created at
at the different memory location the same memory location

Recursion
Any function which calls itself is called a recursive function, and such function calls are
called recursive calls. Recursion involves several numbers of recursive calls. Recursion code
is shorter than iterative code however it is difficult to understand.
Recursion cannot be applied to all the problems, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.
In the following example, recursion is used to calculate the factorial of a number.
#include <iostream>
using namespace std;
int fact (int);
int main()
{
int n,f;
cout<<"Enter the number whose factorial you want to calculate?";
cin>>n;
f = fact(n);
cout<<"factorial = "<<f;
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
Notes Prepared By : Sarvagya Jain
Array
An array is defined as the collection of similar types of data items stored at contiguous
memory locations. Arrays are the derived data type which can store the primitive type of data
such as int, char, double, float, etc. It also has the capability to store the collection of derived
data types, such as pointers, structure, etc. The array is the simplest data structure where each
data element can be randomly accessed by using its index number.
Declaration of Array
data_type array_name[array_size];
the example to declare the array.
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of Array
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;

// array example
#include<iostream>
using namespace std;
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
cout<<" \n"<<marks[i];
}//end of for loop
return 0;
}
Output
80
Notes Prepared By : Sarvagya Jain
60
70
85
75
Declaration with Initialization
We can initialize the array at the time of declaration.
int marks[5]={20,30,40,50,60};
In such a case, there is no requirement to define the size.
int marks[]={20,30,40,50,60};
//program to declare and initialize the array.
#include<iostream>
using namespace std;
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
cout<<" \n"<<marks[i];
}
return 0;
}
Output
20
30
40
50
60
Multidimensional Array -Two Dimensional Array
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns.
Declaration of two dimensional Array.
The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
example.
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array
The two-dimensional array can be declared and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//Two-dimensional array example.
#include<iostream>
using namespace std;
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
for(i=0;i<4;i++){
Notes Prepared By : Sarvagya Jain
for(j=0;j<3;j++){
coût<<arr[i][j];
}
}
return 0;
}
Output
1
2
3
2
3
4
3
4
5
4
5
6
String:
Strings are actually a one-dimensional array of characters terminated by a null character '\0'.
The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the
string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array.
#include <iostream>
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout<<"Greeting message: \n" <<greeting);
return 0;
}
Notes Prepared By : Sarvagya Jain
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings −
Sr.No. Function Purpose

1 strcpy(s1, s2);
Copies string s2 into string s1.

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

The following example uses some of the above-mentioned functions −


#include <iostream>
#include <string.h>
using namespace std;
int main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
cout<<"\n strcpy( str3, str1) : " <<str3;
/* concatenates str1 and str2 */
strcat( str1, str2);
cout<<"\n strcat( str1, str2): " <<str1;
/* total length of str1 after concatenation */
len = strlen(str1);
cout<<"\n strlen(str1) :" <<len;
return 0;
}
When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
Notes Prepared By : Sarvagya Jain
Pointer:
Pointers (pointer variables) are special variables that are used to store addresses rather than
values.
Pointer Syntax
int* p;
Assigning addresses to Pointers
int* pc, c;
c = 5;
pc = c;
Get Value of Thing Pointed by Pointers
To get the value of the thing pointed by the pointers, we use the * operator. For example:
int* pc, c;
c = 5;
pc = c;
cout<< *pc; // Output: 5
Example:
//Working of Pointers
#include <iostream>
using namespace std;
int main()
{
int* pc, c;
c = 22;
cout<<"Address of c\n"<<c;
cout<<"Value of c: \n"<<c;
pc = c;
cout<<"\n Address of pointer pc:" <<pc;
cout<<"\n Content of pointer pc: " <<*pc;
c = 11;
cout<<"\n Address of pointer pc:"<< pc;
cout<<"\n Content of pointer pc: "<< *pc;
*pc = 2;
cout<<"\n Address of c:" <<c;
cout<<"\n Value of c: " <<c;
return 0;
}
Output
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2
Notes Prepared By : Sarvagya Jain
Double Pointer :(pointer to pointer)
define a pointer to store the address of another pointer. Such a pointer is known as a double
pointer (pointer to pointer). The first pointer is used to store the address of a variable whereas
the second pointer is used to store the address of the first pointer. Let's understand it by the
diagram given below.
pointer to pointer in c
The syntax of declaring a double pointer is given below.
int **p; // pointer to a pointer which is pointing to an integer.
Consider the following example.
#include<iostream>
using namespace std;
void main ()
{
int a = 10;
int *p;
int **pp;
p = a; // pointer p is pointing to the address of a
pp = p; // pointer pp is a double pointer pointing to the address of pointer p
cout<<"\n address of a:”<<p; // Address of a will be printed
cout<<"\n address of p:"<<pp; // Address of p will be printed
cout<<"\n value stored at p: "<<*p; // value stored at the address contained by p i.e. 10 will
be printed
cout<<"\n value stored at pp:"<<**pp; // value stored at the address contained by the
pointer stored at pp
}
Output
address of a: d26a8734
address of p: d26a8738
value stored at p: 10
value stored at pp: 10
Pointers to functions
A pointer to a function points to the address of the executable code of the function. You can
use pointers to call functions and to pass functions as arguments to other functions.
The type of a pointer to a function is based on both the return type and parameter types of the
function.
Declaration of a function pointer
Syntax of function pointer
1. return type (*ptr_name)(type1, type2…);
For example:
1. int (*ip) (int);
In the above declaration, *ip is a pointer that points to a function which returns an int value
and accepts an integer value as an argument.
Calling a function using a function pointer is given below:
1. result = (*fp)( a , b); // Calling a function using function pointer.
Or
1. result = fp(a , b);
Notes Prepared By : Sarvagya Jain
//understand the function pointer through an example.
#include <iostream>
using namespace std;
int add(int,int);
int main()
{
int a,b;
int (*ip)(int,int);
int result;
cout<<"Enter the values of a and b : ";
cin>>a>>b;
ip=add;
result=(*ip)(a,b);
cout<<"Value after addition is : "<<result;
return 0;
}
int add(int a,int b)
{
int c=a+b;
return c;
}
Return pointer from functions
Declaration of function that returns pointer Following is the function declaration syntax that
will return pointer.
returnType *functionName(param list);
int *f(int a);
f is interpreted as a function that takes an int as argument, and returns a pointer to an int.
In the following example the getMax() function returns an integer pointer i.e., address of a
variable that holds the greater value.
#include <iostream>
using namespace std;
// function declaration
int *getMax(int *, int *);
int main() {
// integer variables
int x = 100;
int y = 200;
// pointer variable
int *max = NULL;
/**
* get the variable address that holds the greater value
* for this we are passing the address of x and y
* to the function getMax()
*/
max = getMax(x, y);
// print the greater value
Notes Prepared By : Sarvagya Jain
cout<<"\n Max value:" <<*max;
return 0;
}
// function definition
int *getMax(int *m, int *n) {
/**
* if the value pointed by pointer m is greater than n
* then, return the address stored in the pointer variable m
*/
if (*m > *n) {
return m;
}
/**
* else return the address stored in the pointer variable n
*/
else {
return n;
}

}
Output:
Max value: 200
Pointer to an Array | Array Pointer
An array name is a constant pointer itself to the first element of the array. Therefore, in the
declaration −
arr is a pointer to arr[0], which is the address of the first element of the array balance. Thus,
the following program fragment assigns p as the address of the first element of arr −
int arr[5] = {10, 20, 30, 40, 50};
int *p=arr;
Once you store the address of the first element in 'p', you can access the array elements using
*p, *(p+1), *(p+2) and so on.
We can also point the whole array using pointers.
int arr[5] = {10, 20, 30, 40, 50};
int (*ptr)[5];
ptr = arr;
Where, ptr points the entire array.
Dereferencing the array pointer
Since ptr is an array pointer,
*ptr will be again an address which is the address of the first element in the array.
**ptr will be the value stored at the address.
Example //Pointer to an array example
#include<iostream>
using namespace std;
int main()
{
int arr[5]={10, 20, 30, 40, 50};
Notes Prepared By : Sarvagya Jain
int (*ptr)[5]; //pointer to an array of 5 integers
int *p;
ptr = arr; //ptr references the whole array
p=arr;
// *ptr is a pointer to the whole array Address *ptr+1 will point the next block of 5
elements Address
cout<<"\n"<<ptr<<”,”<<ptr+1;
// *ptr is a pointer to the first element Address in the array *ptr+1 will point the next
element Address in the array
cout<<"\n"<<*ptr<<”,”<<*ptr+1;
// *p or **ptr is a pointer to the first element in the array, *(p+1)or *(*ptr+1) will point
the next element in the array
cout<<"\n"<<*p<<”,”<<*(p+1);
cout<<" \n"<<**ptr<<”,”<<*(*ptr+1);
return 0;
}
Array of pointers
Like an array of variables, we can also use array of pointers array of pointer
Let's create an array of 5 pointers.
int *arr[5];
Where arr[0] will hold one integer variable address, arr[1] will hold another integer variable
address and so on.
Dereference - Accessing the value stored at the pointer.
Since each array index pointing to a variable's address, we need to use *arr[index] to access
the value stored at the particular index's address.
arr[index] will have address
*arr[index] will print the value.
Example
// Program : Array of Pointers
#include<iostream> using namespace std;
#define size 5
int main()
{
int *arr[size];
int a = 10, b = 20, c = 30, d = 40, e = 50, i;
arr[0] = a;
arr[1] = b;
arr[2] = c;
arr[3] = d;
arr[4] = e;
cout<<"\nAddress of a ="<<arr[0];
cout<<"\nAddress of b ="<<arr[1]);
cout<<"\nAddress of c ="<<arr[2]);
cout<<"\nAddress of d ="<<arr[3]);
cout<<"\nAddress of e ="<<arr[4]);
for(i = 0; i < size; i++)
Notes Prepared By : Sarvagya Jain
cout<<"\n"<<*arr[i];
return 0;
}
Dynamic memory allocation.
The concept of dynamic memory allocation enables the programmer to allocate memory at
runtime. Dynamic memory allocation in C and C++ language is possible by 4 functions of the
cstdlib header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc() functions.

free() frees the dynamically allocated memory.

malloc() function
The malloc() function allocates a single block of requested memory. It doesn't initialize
memory at execution time, so it has garbage value initially. It returns NULL if memory is not
sufficient.
The syntax of malloc() function is given below:
ptr=(cast-type*)malloc(byte-size)
Let's see the example of malloc() function.
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
int n,i,*ptr,sum=0;
cout<<"Enter number of elements: ";
cin>>n;
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
cout<<"Sorry! unable to allocate memory");
exit(0);
}
cout<<"Enter elements of array: ";
for(i=0;i<n;++i)
{
cin>>ptr+i;
sum+=*(ptr+i);
}
Notes Prepared By : Sarvagya Jain
cout<<"Sum="<<sum;
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
calloc() function
The calloc() function allocates multiple blocks of requested memory. It initially initialises all
bytes to zero.
It returns NULL if memory is not sufficient.
The syntax of calloc() function is given below:
ptr=(cast-type*)calloc(number, byte-size)
Let's see an example of the calloc() function.
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
int n,i,*ptr,sum=0;
cout<<"Enter number of elements: ";
cin>>n;
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
cout<<"Sorry! unable to allocate memory";
exit(0);
}
cout<<"Enter elements of array: ";
for(i=0;i<n;++i)
{
cin>>ptr+i;
sum+=*(ptr+i);
}
cout<<"Sum="<<sum;
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
Notes Prepared By : Sarvagya Jain
realloc() function
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by
realloc() function. In short, it changes the memory size.
Let's see the syntax of realloc() function.
1. ptr=realloc(ptr, new-size)
free() function
The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until the program exit.
Let's see the syntax of free() function.
1. free(ptr)
Structure
Structure is a user-defined data type that enables us to store the collection of different data
types. Each element of a structure is called a member. Structures ca; simulate the use of
classes and templates as it can store various information.
The ,struct keyword is used to define the structure. Let's see the syntax to define the structure
in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Declaring structure variable
We can declare a variable for the structure so that we can access the member of the structure
easily. There are two ways to declare structure variable:
1. By struct keyword within main() function:--
struct employee
{ int id;
char name[50];
float salary;
}
int main ()
{
struct employee e1, e2;
}
2. By declaring a variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
Accessing members of the structure
There are two ways to access structure members:
1. By . (member or dot operator)
Notes Prepared By : Sarvagya Jain
2. By -> (structure pointer operator)
Let's see the code to access the id member of p1 variable by. (member) operator.
p1.id
Structure example
Let's see a simple example of structure in C++ language.
#include<iostream>
#include <string.h>
using namespace std;
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
//printing first employee information
cout<< "\nemployee 1 id :"<< e1.id;
cout<< "\nemployee 1 name : “ <<e1.name;
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
Array of Structures
An array of structures can be defined as the collection of multiple structures variables where
each variable contains information about different entities. The array of structures are used to
store information about multiple entities of different data types. The array of structures is also
known as the collection of structures.
#include<iostream>
using namespace std;
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
cout<<"Enter Records of 5 students";
for(i=0;i<5;i++){
cout<<"\nEnter Rollno:";
cin>>st[i].rollno;
cout<<"\nEnter Name:";
cin>>st[i].name;
Notes Prepared By : Sarvagya Jain
}
cout<<"\nStudent Information List:";
for(i=0;i<5;i++){
cout<<"\n Rollno: Name:"<<st[i].rollno<<st[i].name;
}
return 0;
}
In the above code, the union has two members, i.e., 'a' and 'b'. The 'var' is a variable of union
abc type. In the main() method, we assign the 66 to 'a' variable, so var.a will print 66 on the
screen. Since both 'a' and 'b' share the memory location, var.b will print 'B' (ascii code of 66).
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
Structure Pointer
The structure pointer points to the address of a memory block where the Structure is being
stored. Like a pointer that tells the address of another variable of any data type (int, char,
float) in memory. And here, we use a structure pointer which tells the address of a structure in
memory by pointing pointer variable ptr to the structure variable.
Declare a Structure Pointer
The declaration of a structure pointer is similar to the declaration of the structure variable. So,
we can declare the structure pointer and variable inside and outside of the main() function. To
declare a pointer variable in C, we use the asterisk (*) symbol before the variable's name.
struct structure_name *ptr;
Initialization of the Structure Pointer
ptr = structure_variable;
Access Structure member using pointer:
There are two ways to access the member of the structure using Structure pointer:
1. Using ( * ) asterisk or indirection operator and dot ( . ) operator.
2. Using arrow ( -> ) operator or membership operator.
Program to access the structure member using structure pointer and the(->) operator
#include <iostream>
using namespace std;
Notes Prepared By : Sarvagya Jain
// create Employee structure
struct Employee
{
// define the member of the structure
char name[30];
int id;
int age;
char gender[30];
char city[40];
};
// define the variables of the Structure with pointers
struct Employee emp1, emp2, *ptr1, *ptr2;
int main()
{
// store the address of the emp1 and emp2 structure variable
ptr1 = emp1;
ptr2 = emp2;
cout<<" Enter the name of the Employee (emp1): ";
cin>> ptr1->name;
cout<<" Enter the id of the Employee (emp1): ";
cin>> ptr1->id;
cout<<" Enter the age of the Employee (emp1): ";
cin>> ptr1->age;
cout<<" Enter the gender of the Employee (emp1): ";
cin>> ptr1->gender;
cout<<" Enter the city of the Employee (emp1): ";
cin>> ptr1->city;
cout<<" \n Second Employee: \n";
cout<<" Enter the name of the Employee (emp2): ";
cin>> ptr2->name;
cout<<" Enter the id of the Employee (emp2): ";
cin>> ptr2->id)
cout<<" Enter the age of the Employee (emp2): ";
cin>> ptr2->age;
cout<<" Enter the gender of the Employee (emp2): ";
cin>> ptr2->gender);
cout<<" Enter the city of the Employee (emp2): ";
cin>> ptr2->city;
cout<<"\n Display the Details of the Employee using Structure Pointer";
cout<<"\n Details of the Employee (emp1) \n";
cout<<" \n Name:" <<ptr1->name;
cout<<" \n Id: " <<ptr1->id;
cout<<" \nAge: " <<ptr1->age;
cout<<" \n Gender: " <<ptr1->gender;
cout<<" \nCity: "<< ptr1->city;
cout<<"\n Details of the Employee (emp2) \n";
Notes Prepared By : Sarvagya Jain
cout<<" \n Name:" <<ptr2->name;
cout<<" \n Id: " <<ptr2->id;
cout<<" \nAge: "<<ptr2->age;
cout<<" \nGender:"<< ptr2->gender;
cout<<" \nCity:" <<ptr2->city;
return 0;
}

Difference between structured vs unstructured programming:

Structured Programming Unstructured Programming

It is basically a subset of procedural


It is basically a procedural program.
programs.

In this, programmers are allowed to In this, programmers are not allowed code to
code a program simply by dividing divide programs into small units. Instead, the
the program into modules or smaller program should be written as a single
units. continuous block without any breakage.

It is more user-friendly and easy to It is less user-friendly and a little hard to


understand as compared to understand as compared to structured
unstructured programming. programming.

It is easier to learn and follow. It is difficult to learn and follow

Its advantages include reducing


complexity, facilitating debugging,
Its advantages include its speed.
increasing programmer productivity
programs, etc.

Such programs can be used for small Such programs cannot be used for medium and
and medium-scale projects and also complex projects. Instead, they can be used for
for complex projects. small and easier projects.

These programs do not allow code


These programs allow code duplication.
duplication.

Structured programs use a greater


Unstructured programs use a limited number of
number of data types as compared to
data types as compared to structured programs.
unstructured programs.
Notes Prepared By : Sarvagya Jain

It does not use GOTO to control the


flow of execution. Instead, it uses It uses GOTO to control the flow of execution.
loops.

It produces readable code. It hardly produces readable code.

It does not provide full freedom to


It provides full freedom to programmers to
programmers to program as they
program as they want.
want.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects. It simplifies software development and maintenance by providing some
concepts:
Object
Any entity that has state and behavior is known as an object. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.A class can also be defined as a
blueprint from which you can create an individual object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.

Comparison between Procedural Programming and Object Oriented Programming:


Notes Prepared By : Sarvagya Jain
Procedural Oriented Programming Object Oriented Programming

In object oriented programming, a


In procedural programming, a program is
program is divided into small parts called
divided into small parts called functions.
objects.

Procedural programming follows a top Object oriented programming follows a


down approach. bottom up approach.

Object oriented programming have access


There is no access specifier in procedural
specifiers like private, public, protected
programming.
etc.

Adding new data and functions is not easy. Adding new data and functions is easy.

Procedural programming does not have


Object oriented programming provides
any proper way for hiding data so it is less
data hiding so it is more secure.
secure.

In procedural programming, overloading is Overloading is possible in object oriented


not possible. programming.

In procedural programming, function is In object oriented programming, data is


more important than data. more important than function.

Procedural programming is based on Object oriented programming is based on


unreal world. real world.

Examples: C, FORTRAN, Pascal, Basic


Examples: C++, Java, Python, C# etc.
etc.

Abstract Data Types


Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set
of values and a set of operations.

The definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented. It does not specify how data will be organized in memory
and what algorithms will be used for implementing the operations. It is called “abstract”
because it gives an implementation-independent view. The process of providing only the
essentials and hiding the details is known as abstraction.

References in C++
Notes Prepared By : Sarvagya Jain
When a variable is declared as a reference, it becomes an alternative name for an existing
variable. A variable can be declared as a reference by putting ‘&’ in the declaration.
#include<iostream>
using namespace std;
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
ref = 20;
cout << "x = " << x << endl ;
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << endl ;
return 0;
}
Output:
x = 20
ref = 30

Scope resolution operator in C++


1) To access a global variable when there is a local variable with same name:
#include<iostream>
using namespace std;
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
Output:
Value of global x is 0
Value of local x is 10
2) To define a function outside a class.
#include<iostream>
using namespace std;
class A
{
public:
// Only declaration
void fun();
};
// Definition outside class using ::
void A::fun()
Notes Prepared By : Sarvagya Jain
{
cout << "fun() called";
}
int main()
{
A a;
a.fun();
return 0;
}
Output:
fun() called
3) To access a class’s static variables.
4) In case of multiple Inheritance:
Notes Prepared By: Sarvagya Jain

Unit -2
Specification of Class:
A class is used to specify the form of an object and it combines data representation and
methods for manipulating that data into one neat package. The data and functions within a
class are called members of the class.

C++ Class Definitions:


A class definition starts with the keyword class followed by the class name; and the class
body, enclosed by a pair of curly braces. A class definition must be followed either by a
semicolon or a list of declarations. For example, we defined the Box data type using the
keyword class as follows −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
Define C++ Objects
A class provides the blueprints for objects, so basically an object is created from a class. We
declare objects of a class with exactly the same sort of declaration that we declare variables
of basic types. Following statements declare two objects of class Box −

Box Box1; // Declare Box1 of type Box


Box Box2; // Declare Box2 of type Box

Accessing the Data Members


The public data members of objects of a class can be accessed using the direct member access
operator (.).

Box1.height = 5.0;

Member Functions
A member function of a class is a function that has its definition or its prototype within the
class definition like any other variable. It operates on any object of the class of which it is a
member, and has access to all the members of a class for that object.
Defining Member Function:
Member functions can be defined within the class definition or separately using scope
resolution operator : −. Defining a member function within the class definition declares the
function inline, even if you do not use the inline specifier. So either you can define Volume()
function as below −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
Notes Prepared By: Sarvagya Jain
double height; // Height of a box

double getVolume(void) {
return length * breadth * height;
}
};
If you like, you can define the same function outside the class using the scope resolution
operator (::) as follows −
double Box::getVolume(void) {
return length * breadth * height;
}

Example: //Program to demonstrate Class, Object and Member Function


#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

// Member functions declaration


double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
// Member functions definitions
double Box::getVolume(void) {
return length * breadth * height;
}
void Box::setLength( double len ) {
length = len;
}
void Box::setBreadth( double bre ) {
breadth = bre;
}
void Box::setHeight( double hei ) {
height = hei;
}
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
Notes Prepared By: Sarvagya Jain
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
Output:
Volume of Box1 : 210
Volume of Box2 : 1560
Static Members
Static Data Members
We can define class members static using the static keyword. When we declare a member of a
class as static it means no matter how many objects of the class are created, there is only one
copy of the static member.
A static member is shared by all objects of the class. All static data is initialized to zero when
the first object is created, if no other initialization is present.
We can't put it in the class definition but it can be initialized outside the class by using the
scope resolution operator :: to identify which class it belongs to.
Syntax:
static DataType variable name;

Static Members Function


By declaring a function member as static, you make it independent of any particular object
of the class. A static member function can be called even if no objects of the class exist and
the static functions are accessed using only the class name and the scope resolution operator
:: A static member function can only access static data member, other static member
functions and any other functions from outside the class.
Static member functions have a class scope and they do not have access to the pointer of the
class. You could use a static member function to determine whether some objects of the class
have been created or not.
Syntax:
static functionName([Parameter])
{
Notes Prepared By: Sarvagya Jain

}
Example:// Working with static data member and member function.
#include <iostream>
using namespace std;

class Box {
public:
static int objectCount;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume() {
return length * breadth * height;
}
static int getCount() {
return objectCount;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void) {
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects after creating object.
cout << "Final Stage Count: " << Box::getCount() << endl;
return 0;
}
Output:
Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2
Notes Prepared By: Sarvagya Jain
Array of Object:
The Array of Objects stores objects. An array of a class type is also known as an array of
objects.
Syntax
ClassName ObjectName[number of objects];
Example: // Working with Array of Object
#include<iostream>
using namespace std;

class Employee
{
int id;
char name[30];
public:
void getdata();//Declaration of function
void putdata();//Declaration of function
};
void Employee::getdata(){//Defining of function
cout<<"Enter Id : ";
cin>>id;
cout<<"Enter Name : ";
cin>>name;
}
void Employee::putdata(){//Defining of function
cout<<id<<" ";
cout<<name<<" ";
cout<<endl;
}
int main(){
Employee emp[30];
int n, i;
cout << "Enter Number of Employees - ";
cin >> n;

// Accessing the function


for(i = 0; i < n; i++)
emp[i].getdata();

cout << "Employee Data - " << endl;

// Accessing the function


for(i = 0; i < n; i++)
emp[i].putdata();
return 0;
}
Notes Prepared By: Sarvagya Jain

Passing and Returning Objects in C++


we can pass class’s objects as arguments and also return them from a function the same way
we pass and return other variables. No special keyword or header file is required to do so.
Passing an Object as argument
To pass an object as an argument we write the object name as the argument while calling the
function the same way we do it for other variables.
Syntax:

function_name(object_name);
Returning Object as argument
Syntax:

object = return object_name;


Example: // Working with Object as argument and returning Object
#include <iostream>
using namespace std;
class Example {
public:
int a;
// This function will take
// object as arguments and
// return object
Example add(Example Ea, Example Eb)
{
Example Ec;
Ec.a = Ea.a + Eb.a;
// returning the object
return Ec;
}
};
int main()
{
Example E1, E2, E3;
// Values are initialized for both objects
E1.a = 50;
E2.a = 100;
E3.a = 0;
cout << "Initial Values \n";
cout << "Value of object 1: " << E1.a<< ", \nobject 2: " << E2.a<< ", \nobject 3: " << E3.a
<< "\n";
// Passing object as an argument to function add()
E3 = E3.add(E1, E2);
// Changed values after passing object as an argument
cout << "New values \n";
Notes Prepared By: Sarvagya Jain
cout << "Value of object 1: " << E1.a<< ", \nobject 2: " << E2.a<< ", \nobject 3: " << E3.a
<< "\n";
return 0;
}
Output:
Output
Initial Values
Value of object 1: 50,
object 2: 100,
object 3: 0
New values
Value of object 1: 50,
object 2: 100,
object 3: 150

Inline Function:
C++ provides inline functions to reduce the function call overhead. Inline function is a
function that is expanded in line when it is called. When the inline function is called, the
whole code of the inline function gets inserted or substituted at the point of inline function
call. This substitution is performed by the C++ compiler at compile time. Inline function may
increase efficiency if it is small.
The syntax for defining the function inline is:
inline return-type function-name(parameters)
{
// function code
}
Compiler may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist in the
function body.
5) If a function contains a switch or goto statement.
Example: //working with inline function
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
} //Output: The cube of 3 is: 27
Notes Prepared By: Sarvagya Jain

Default Arguments in C++:


A default argument is a value provided in a function declaration that is automatically
assigned by the compiler if the caller of the function doesn’t provide a value for the argument
with a default value. In case any value is passed the default value is overridden.
// CPP Program to demonstrate Default Arguments
#include <iostream>
using namespace std;
int sum(int x, int y, int z = 0, int w = 0)
{
return (x + y + z + w);
}
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

Friend class and function in C++


Friend Class A friend class can access private and protected members of other class in which
it is declared as friend. It is sometimes useful to allow a particular class to access private
members of another class.
Syntax:
class B
{
friend class A
};
Example: // Working with Friend class
// C++ program to demonstrate the working of friend class

#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
private:
Notes Prepared By: Sarvagya Jain
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
int add() {
ClassA objectA;
return objectA.numA + numB;
}
};
int main() {
ClassB objectB;
cout << "Sum: " << objectB.add();
return 0;
}
Output
Sum: 13

Friend Function Like friend class, a friend function can be given a special grant to access
private and protected members. A friend function can be:
a) A member of another class
b) A global function
Syntax:
class A
{
Friend return type FunctionName(class Obj);
};
return type FunctionName(class Obj)
{
}
Example: // Working with Friend Function
#include <iostream>
using namespace std;
Notes Prepared By: Sarvagya Jain
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;
}
int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;
}
Output
Distance: 5

Constructor
A constructor is a special type of member function of a class which initializes objects of a
class. In C++, Constructor is automatically called when an object(instance of class) is
created. It is a special member function of the class because it does not have any return type.
Rules apply to C++ constructors:
● The name of the constructor must be identical to the name of the class.
● You must not include any return type, not even void!
● A class can have any number of constructors, including none. The compiler
automatically creates a constructor for a class that has none.
● The default constructor is the one that either has no parameters or it has a parameter
list in which all the parameters use default arguments.
● The copy constructor enables you to create a class instance using an existing instance.
If you do not declare a copy constructor, the compiler creates on for you. The
compiler creates a shallow copy constructor. This constructor simply copies data
members. If your class includes dynamic data (using new, for example) you need to
write your own copy constructor to do a deep copy including dynamic data structures.
● The instantiation of a class (declaring an instance of the class) involves a constructor.
Which constructor is called depends on how many constructors you have declared and
you declared the class instance. For example, instantiation with no arguments will call
the default constructor.
Types of Constructors
Notes Prepared By: Sarvagya Jain
1. Default Constructors: Default constructor is the constructor which doesn’t take any
argument. It has no parameters.
// Cpp program to illustrate the concept of Constructors
#include <iostream>
using namespace std;
class construct
{
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically when the object is created
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}
Output:
a: 10
b: 20

2. Parameterized Constructors: It is possible to pass arguments to constructors. Typically,


these arguments help initialize an object when it is created. To create a parameterized
constructor, simply add parameters to it the way you would to any other function. When you
define the constructor’s body, use the parameters to initialize the object.
/ CPP program to illustrate parameterized constructors
#include <iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
Notes Prepared By: Sarvagya Jain
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}
Output:
p1.x = 10, p1.y = 15

3. Copy Constructor: A copy constructor is a member function which initializes an object


using another object of the same class.
A copy constructor has the following general function prototype:
ClassName (const ClassName &old_obj);
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
// Copy constructor
Point(const Point &p1) {x = p1.x; y = p1.y; }
int getX()
{ return x; }
int getY()
{ return y; }
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here

// Let us access values assigned by constructors


Notes Prepared By: Sarvagya Jain
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
Output:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15
Destructor
Destructor is an instance member function which is invoked automatically whenever an
object is going to be destroyed. Meaning, a destructor is the last function that is going to be
called before an object is destroyed.
The thing is to be noted here, if the object is created by using new or the constructor uses new
to allocate memory which resides in the heap memory or the free store, the destructor should
use delete to free the memory.
Syntax:
~constructor-name();
Rules apply to Destructor:
● The name of the destructor must begin with the tilde character (~). The rest of the
destructor name must be identical to the name of its class.
● Destructor function is automatically invoked when the objects are destroyed.
● It cannot be declared static or const.
● The destructor does not have arguments.
● It has no return type, not even void.
● An object of a class with a Destructor cannot become a member of the union.
● A destructor should be declared in the public section of the class.
● The programmer cannot access the address of the destructor.
//Working with Destructure
#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
Notes Prepared By: Sarvagya Jain
return 0;
}
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

Constructors with Default Arguments:


Default arguments of the constructor are those which are provided in the constructor
declaration. If the values are not provided when calling the constructor the constructor uses
the default arguments automatically.
// An example program to demonstrate the concept default arguments .
#include<iostream>
using namespace std;
class Simple{
int data1;
int data2;
int data3;
public:
Simple(int a, int b=9, int c=8){
data1 = a;
data2 = b;
data3 = c;
}
void printData();

};
void Simple :: printData(){
cout<<"The value of data1, data2 and data3 is "<<data1<<", "<< data2<<" and "<<
data3<<endl;
}
int main(){
Simple s(12, 13);
s.printData();
return 0;
}
Notes Prepared By : Sarvagya Jain

Unit 3
Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism, a person at the same time can have different characteristics. Like
a man at the same time is a father, a husband, an employee. So the same person possesses
different behavior in different situations. This is called polymorphism.
polymorphism is mainly divided into two types:
1. Compile time Polymorphism
2. Runtime Polymorphism
Compile time polymorphism: This type of polymorphism is achieved by function overloading
or operator overloading.
Function Overloading: When there are multiple functions with the same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by
change in number of arguments or/and change in type of arguments.
Operator Overloading: C++ also provides an option to overload operators. For example, we
can make the operator (‘+’) for string class to concatenate two strings. We know that this is
the addition operator whose task is to add two operands. So a single operator ‘+’ when placed
between integer operands , adds them and when placed between string operands, concatenates
them.
Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.
Function overriding: on the other hand occurs when a derived class has a definition for one of
the member functions of the base class. That base function is said to be overridden.

Method overloading: is the process of overloading the method that has the same name but
different parameters. C++ provides this method of overloading features. Method overloading
allows users to use the same name to another method, but the parameters passed to the
methods should be different. The return type of methods can be the same or different.
Syntax:
int sample(a)
{
}
int sample(int a , int b)
{
}
float sample(float a, float b)
{
}
Example:
#include <iostream>
using namespace std;
class addition
{
public:
Notes Prepared By : Sarvagya Jain
int addMethod(int x, int y)
{
return x + y;
}
int addMethod(int x, int y, int z)
{
return x + y + z;
}
};
int main(void)
{
addition add;
cout << add.addMethod(2, 3) << endl;
cout << add.addMethod(2, 3, 6) << endl;
return 0;
}
Output
5
11
Operators Overloading
Operator overloading is a compile-time polymorphism in which the operator is overloaded to
provide the special meaning to the user-defined data type. Operator overloading is used to
overload or redefine most of the operators available in C++. It is used to perform the
operation on the user-defined data type. For example, C++ provides the ability to add the
variables of the user-defined data type that is applied to the built-in data types.
The advantage of Operators overloading is to perform different operations on the same
operand.
Operator that cannot be overloaded are as follows:
● Scope operator (::)
● Sizeof
● member selector(.)
● member pointer selector(*)
● ternary operator(?:)
Syntax of Operator Overloading
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
Where the return type is the type of value returned by the function.
class_name is the name of the class.
operator op is an operator function where op is the operator being overloaded, and the
operator is the keyword.

Rules for Operator Overloading:


Notes Prepared By : Sarvagya Jain
● Existing operators can only be overloaded, but the new operators cannot be
overloaded.
● The overloaded operator contains atleast one operand of the user-defined data type.
● We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators.
● When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
● When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit
arguments.
Unary Operators Overloading
The unary operators operate on a single operand and following are the examples of Unary
operators −
The increment (++) and decrement (--) operators.
The unary minus (-) operator.
The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this
operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometimes they
can be used as postfix as well like obj++ or obj--.
// Overload ++ when used as prefix and postfix
#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;
}

// Overload ++ when used as postfix


void operator ++ (int) {
value++;
}
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1;
Notes Prepared By : Sarvagya Jain
// Call the "void operator ++ (int)" function
count1++;
count1.display();
// Call the "void operator ++ ()" function
++count1;
count1.display();
return 0;
}
Output
Count: 6
Count: 7
Binary Operator Overloading:
An operator which contains two operands to perform a mathematical operation is called the
Binary Operator Overloading. It is a polymorphic compile technique where a single operator
can perform various functionalities by taking two operands from the programmer or user.
There are multiple binary operators like +, -, *, /, etc., that can directly manipulate or
overload the object of a class.
Syntax of the Binary Operator Overloading
Following is the Binary Operator Overloading syntax in the C++ Programming language.

return_type :: operator binary_operator_symbol (arg)


{
// function definition
}
// program to overload the binary operators(+).
#include <iostream>
using namespace std;
class A
{

int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};

void A :: operator+(A a)
{

int m = x+a.x;
Notes Prepared By : Sarvagya Jain
cout<<"The result of the addition of two objects is : "<<m;

}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}
Output:

The result of the addition of two objects is : 9

// program to overload the binary Relational operators(>).


#include <iostream>
using namespace std;
class Student{
int feet = 0; //can be b/w 0 & infinity
int inches = 0; // can be b/w 0 & 12

public:
void getHeight(int f, int i)
{
//feet can be b/w [0,infinity]
//inches can be b/w [0,12)
if(f >= 0 && (i >= 0 && i <12))
{
feet = f;
inches = i;
}
else
{
cout << "Invalid height format" << endl;
cout << "By default 0,0 will be taken" << endl; } }
bool operator >(Student s2)
{
if(feet > s2.feet)
return true;

if(feet == s2.feet && inches > s2.inches)


{
return true;
}
Notes Prepared By : Sarvagya Jain
return false;
}

};

int main()
{
Student s1,s2;

s1.getHeight(5,10);
s2.getHeight(6,1);

if(s1 > s2)


cout << "Student 1 is taller" << endl; else if(s2 > s1)
cout << "Student 2 is taller" << endl;
else
cout << "Both have equal height" << endl;

return 0;
}

Output –
Student 2 is taller

// program to overload the Assignment operators(=).


#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12

public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
void operator = (Distance D ) {
Notes Prepared By : Sarvagya Jain
feet = D.feet;
inches = D.inches;
}

// method to display distance


void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;
}
};

int main() {
Distance D1(11, 10), D2(5, 11);

cout << "First Distance : ";


D1.displayDistance();
cout << "Second Distance :";
D2.displayDistance();

// use assignment operator


D1 = D2;
cout << "First Distance :";
D1.displayDistance();

return 0;
}
Output:
First Distance : F: 11 I:10
Second Distance :F: 5 I:11
First Distance :F: 5 I:11

Pitfalls of operator overloading:


● Conditional [?:], size of, scope(::), Member selector(.), member pointer selector(.*)
and the casting operators.
● We can only overload the operators that exist and cannot create new operators or
rename existing operators.
● At least one of the operands in overloaded operators must be user-defined, which
means we cannot overload the minus operator to work with one integer and one
double. However, you could overload the minus operator to work with an integer and
a mystring.
● It is not possible to change the number of operands an operator supports.
● All operators keep their default precedence and associations (what they use for),
which cannot be changed.
● Only built-in operators can be overloaded.
Data Conversion in C++
Notes Prepared By : Sarvagya Jain
A user-defined data types are designed by the user to suit their requirements, the compiler
does not support automatic type conversions for such data types therefore, the user needs to
design the conversion routines by themselves if required.
Conversion of primitive data type to user-defined type: To perform this conversion, the
idea is to use the constructor to perform type conversion during the object creation.
Below is the example to convert int to user-defined data type:
// C++ program to illustrate the
// type-conversion
#include <iostream>
using namespace std;
class Time {
int hour;
int mins;

public:
// Default Constructor
Time()
{
hour = 0;
mins = 0;
}
// Parameterized Constructor
Time(int t)
{
hour = t / 60;
mins = t % 60;
}
// Function to print the value of class variables
void Display()
{
cout << "Time = " << hour<< " hrs and " << mins << " mins\n";
}
};
int main()
{
// Object of Time class
Time T1;
int dur = 95;
// Conversion of int type to class type
T1 = dur;
T1.Display();
return 0;
}
Output
Time = 1 hrs and 35 mins
Notes Prepared By : Sarvagya Jain

Conversion of class object to primitive data type: In this conversion, the from type is a
class object and the to type is primitive data type. The normal form of an overloaded casting
operator function, also known as a conversion function. Below is the syntax for the same:
Syntax:
operator typename()
{
// Code
}
Now, this function converts a user-defined data type to a primitive data type. For Example,
the operator double() converts a class object to type double, the operator int() converts a class
type object to type int, and so on.
// C++ program to illustrate the
// above conversion
#include <bits/stdc++.h>
using namespace std;

class Time {
int hrs, mins;
public:
// Constructor
Time(int, int);
// Casting operator
operator int();
// Destructor
~Time()
{
cout << "Destructor is called." << endl;
}
};
// Function that assigns value to the member variable of the class
Time::Time(int a, int b)
{
hrs = a;
mins = b;
}

// int() operator is used for Data conversion of class to primitive


Time::operator int()
{
cout << "Conversion of Class" << " Type to Primitive Type"<< endl;

return (hrs * 60 + mins);


}
// Function performs type conversion from the Time class type object to int data type
Notes Prepared By : Sarvagya Jain
void TypeConversion(int hour, int mins)
{
int duration;
// Create Time Class object
Time t(hour, mins);

// Conversion OR duration = (int)t


duration = t;
cout << "Total Minutes are “ << duration << endl;

// Conversion from Class type to Primitive type


cout << "2nd method operator"<< " overloading " << endl;
duration = t.operator int();
cout << "Total Minutes are "<< duration << endl;
return;
}
int main()
{
// Input value
int hour, mins;
hour = 2;
mins = 20;
// Function call to illustrate type conversion
TypeConversion(hour, mins);
return 0;
}
Output
Conversion of Class Type to Primitive Type
Total Minutes are 140
2nd method operator overloading
Conversion of Class Type to Primitive Type
Total Minutes are 140
Destructor is called.

Type Casting:
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
Implicit Type Conversion Also known as ‘automatic type conversion’.Done by the compiler
on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable with largest
data type.
bool -> char -> short int -> int ->
Notes Prepared By : Sarvagya Jain
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
Example of Type Implicit Conversion:
// An example of implicit conversion
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
}
Output:
x = 107
y=a
z = 108
Explicit Type Conversion: This process is also called type casting and it is user-defined. Here
the user can typecast the result to make it of a particular data type.
This is done by explicitly defining the required type in front of the expression in parenthesis.
This can be also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
Example:
// C++ program to demonstrate explicit type casting
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
Notes Prepared By : Sarvagya Jain
return 0;
}
Output:
Sum = 2
Notes Prepared By : Sarvagya Jain

Unit -4
Inheritance:
The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or
Super class.
Implementing inheritance in C++: For creating a sub-class which is inherited from the base
class we have to follow the below syntax.
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Here, subclass_name is the name of the sub class, access_mode is the mode in which you
want to inherit this sub class for example: public, private etc. and base_class_name is the
name of the base class from which you want to inherit the sub class.

Modes of Inheritance
● Public mode: If we derive a sub class from a public base class. Then the public
member of the base class will become public in the derived class and protected
members of the base class
will become protected in the
derived class.
● Protected mode: If we
derive a sub class from a
Protected base class. Then
both public member and
protected members of the
base class will become
protected in the derived class.
● Private mode: If we derive a sub class from a Private base class. Then both public
member and protected members of the base class will become Private in derived class.

Types of Inheritance in C++


1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one
class. i.e. one sub class is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
Notes Prepared By : Sarvagya Jain
Example:
// C++ program to explain Single inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
// sub class derived from a single base classes
class Car: public Vehicle{
};

// main function
int main()
{
// creating object of sub class will invoke the constructor of base classes
Car obj;
return 0;
}
Output
This is a Vehicle
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can
inherit from more than one classes. i.e one sub class is inherited from more than one
base classes.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
Example:
// C++ program to explain multiple inheritance
#include <iostream>
using namespace std;
// first base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
Notes Prepared By : Sarvagya Jain
// second base class
class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle" << endl;
}
};
// sub class derived from two base classes
class Car: public Vehicle, public FourWheeler {

};
// main function
int main()
{
// creating object of sub class will invoke the constructor of base classes
Car obj;
return 0;
}
Output
This is a Vehicle
This is a 4 wheeler Vehicle

3. Multilevel Inheritance: In this type of inheritance, a derived class is created from


another derived class.
Example:
// C++ program to implement Multilevel Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
// first sub_class derived from class vehicle
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
Notes Prepared By : Sarvagya Jain
};
// sub class derived from the derived base class fourWheeler
class Car: public fourWheeler{
public:
Car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels

4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is
inherited from a single base class. i.e. more than one derived class is created from a
single base class.

Example:
// C++ program to implement Hierarchical Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

// first sub class


class Car: public Vehicle
{
Notes Prepared By : Sarvagya Jain
};

// second sub class


class Bus: public Vehicle
{

};

// main function
int main()
{
// creating object of subclass will
// invoke the constructor of base class
Car obj1;
Bus obj2;
return 0;
}
Output
This is a Vehicle
This is a Vehicle

5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining


more than one type of inheritance. For example: Combining Hierarchical inheritance
and Multiple Inheritance.
Example:
// C++ program for Hybrid Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
//base class
class Fare
{
public:
Fare()
{
cout<<"Fare of Vehicle\n";
}
Notes Prepared By : Sarvagya Jain
};
// first sub class
class Car: public Vehicle
{
};

// second sub class


class Bus: public Vehicle, public Fare
{

};
// main function
int main()
{
// creating object of sub class will invoke the constructor of base class
Bus obj1;
Car Obj2;
return 0;
}
Output
This is a Vehicle
Fare of Vehicle
This is a Vehicle

6. A special case of hybrid inheritance : Multipath inheritance:


A derived class with two base classes and these two base classes have one common
base class is called multipath inheritance. An ambiguity can arrise in this type of
inheritance.
Example:
// C++ program demonstrating ambiguity in Multipath Inheritance
#include <conio.h>
#include <iostream.h>
class ClassA {
public:
int a;
};
class ClassB : public ClassA {
public:
int b;
};
class ClassC : public ClassA {
public:
int c;
};
Notes Prepared By : Sarvagya Jain
class ClassD : public ClassB, public ClassC {
public:
int d;
};

void main()
{

ClassD obj;

// obj.a = 10; //Statement 1, Error


// obj.a = 100; //Statement 2, Error
obj.ClassB::a = 10; // Statement 3
obj.ClassC::a = 100; // Statement 4
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout << "\n A from ClassB : " << obj.ClassB::a;
cout << "\n A from ClassC : " << obj.ClassC::a;
cout << "\n B : " << obj.b;
cout << "\n C : " << obj.c;
cout << "\n D : " << obj.d;
}
Output:

A from ClassB : 10
A from ClassC : 100
B : 20
C : 30
D : 40
In the above example, both ClassB & ClassC inherit ClassA, they both have single
copy of ClassA. However ClassD inherit both ClassB & ClassC, therefore ClassD
have two copies of ClassA, one from ClassB and another from ClassC.
If we need to access the data member a of ClassA through the object of ClassD, we
must specify the path from which a will be accessed, whether it is from ClassB or
ClassC, bco’z compiler can’t differentiate between two copies of ClassA in ClassD.
There are 2 ways to avoid this ambiguity:
Avoiding ambiguity using scope resolution operator:
Using scope resolution operator we can manually specify the path from which data
member a will be accessed, as shown in statement 3 and 4, in the above example.
Avoiding ambiguity using virtual base class:
Example:
#include<iostream.h>
#include<conio.h>
Notes Prepared By : Sarvagya Jain
class ClassA
{
public:
int a;
};

class ClassB : virtual public ClassA


{
public:
int b;
};
class ClassC : virtual public ClassA
{
public:
int c;
};

class ClassD : public ClassB, public ClassC


{
public:
int d;
};

void main()
{

ClassD obj;

obj.a = 10; //Statement 3


obj.a = 100; //Statement 4

obj.b = 20;
obj.c = 30;
obj.d = 40;

cout<< "\n A : "<< obj.a;


cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;

}
Output:

A : 100
B : 20
Notes Prepared By : Sarvagya Jain
C : 30
D : 40

Nested Classes / Class within class :


A nested class is a class which is declared in another enclosing class. A nested class is
a member and as such has the same access rights as any other member. The members
of an enclosing class have no special access to members of a nested class; the usual
access rules shall be obeyed.
A program that demonstrates nested classes in C++
#include<iostream>
using namespace std;
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n;
}
void putdata() {
cout<<"The number is "<<num;
}
};
};
int main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
}
Output
Nested classes in C++
The number is 9

Function Overriding:
When a derived class or child class defines a function that is already defined in the
base class or parent class, it is called function overriding in C++. Function overriding
helps us achieve runtime polymorphism. It enables programmers to perform the
specific implementation of a function already used in the base class.
// C++ program to demonstrate function overriding
#include <iostream>
using namespace std;
class Base {
Notes Prepared By : Sarvagya Jain
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;
derived1.print();
derived1.Base::print();
return 0;
}
Output
Derived Function
Base Function

Access Overridden Function in C++


To access the overridden function of the base class, we use the scope resolution
operator ::.
Syntax :
// access function of the Base class
derivedObject.BaseClass::FunctionName();

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.
Syntax:
// pointer of Base type that points to derivedObject
Base* ptr = &derivedObject;
// call function of Base class using ptr
ptr->FunctionName();
Notes Prepared By : Sarvagya Jain
Unit 5
Pointers to Objects:
You can access an object either directly, or by using a pointer to the object.To access an element of
an object when using the actual object itself, use the dot operator.
To access a specific element of an object when using a pointer to the object, you must use the arrow
operator.
Syntax : class-name ∗ object-pointer ;
/* working with pointer to object
#include<iostream.h>
#include<conio.h>
class Time
{
short int hh, mm, ss;
public:
Time()
{
hh = mm = ss = 0;
}
void getdata(int i, int j, int k)
{
hh = i;
mm = j;
ss = k;
}
void prndata(void)
{
cout<<"\nTime is "<<hh<<":"<<mm<<":"<<ss<<"\n";
}
};
void main()
{
clrscr();
Time T1, *tptr;
cout<<"Initializing data members using the object, with values 12, 22, 11\n";
T1.getdata(12,22,11);
cout<<"Printing members using the object ";
T1.prndata();
tptr = &T1;
cout<<"Printing members using the object pointer ";
tptr->prndata();
cout<<"\nInitializing data members using the object pointer, with values 15, 10, 16\n";
tptr->getdata(15, 10, 16);
cout<<"printing members using the object ";
T1.prndata();
cout<<"Printing members using the object pointer ";
tptr->prndata();
getch();
Notes Prepared By : Sarvagya Jain
}

Pointer to Derived Class in C++


In C++ we are provided with the functionality to point the pointer to derived class or base class. An
example program is shown below to demonstrate the concept of pointer to a derived class in C++.
#include<iostream.h>
class base
{
public:
int n1;
void show()
{
cout<<”\nn1 = “<<n1;
}
};
class derive : public base
{
public:
int n2;
void show()
{
cout<<”\nn1 = “<<n1;
cout<<”\nn2 = “<<n2;
}
};
int main()
{
base b;
base *bptr; //base pointer
cout<<”Pointer of base class points to it”;
bptr=&b; //address of base class
bptr->n1=44; //access base class via base pointer
bptr->show();
derive d;
cout<<”\n”;
bptr=&d; //address of derive class
bptr->n1=66; //access derive class via base pointer
bptr->show();
return 0;
}
Output
Pointer of base class points to it
n1 = 44
Pointer of base class points to derive class
n1=66

Virtual Function in C++:


Notes Prepared By : Sarvagya Jain
A virtual function is a member function which is declared within a base class and is re-defined
(overridden) by a derived class. When you refer to a derived class object using a pointer or a
reference to the base class, you can call a virtual function for that object and execute the derived
class’s version of the function.
Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at runtime.
Rules for Virtual Functions
● Virtual functions cannot be static.
● A virtual function can be a friend function of another class.
● Virtual functions should be accessed using pointer or reference of base class type to achieve
runtime polymorphism.
● The prototype of virtual functions should be the same in the base as well as derived class.
● They are always defined in the base class and overridden in a derived class. It is not
mandatory for the derived class to override (or re-define the virtual function), in that case,
the base class version of the function is used.
● A class may have a virtual destructor but it cannot have a virtual constructor.
// CPP program to illustrate concept of Virtual Functions
#include <iostream>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base class" << endl;
}
};
class derived : public base {
public:
void print()
{
cout << "print derived class" << endl;
}
};
int main()
{
base *bptr , b;
derived d;
bptr = &d;
bptr = &b;
// virtual function, binded at runtime
bptr->print();

}
Notes Prepared By : Sarvagya Jain
Pure Virtual Functions and Abstract Classes in C++:
Sometimes implementation of all functions cannot be provided in a base class because we don’t
know the implementation. Such a class is called an abstract class. For example, let Shape be a base
class. We cannot provide implementation of function draw() in Shape, but we know every derived
class must have implementation of draw().
A pure virtual function (or abstract function) in C++ is a virtual function for which we can have
implementation, But we must override that function in the derived class, otherwise the derived class
will also become abstract class.A pure virtual function is declared by assigning 0 in declaration.
Example : // working with pure virtual function and abstract class
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};
// This class inherits from Base and implements fun()
class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; }
};
int main(void)
{
Derived d;
d.fun();
return 0;
}
Output:
fun() called

Association:
Association is a simple structural connection or channel between classes and is a relationship where
all objects have their own lifecycle and there is no owner.
Multiple students can associate with a single Department and single student can associate with
multiple Departments, but there is no ownership between the objects and both have their own
lifecycle. Both can create and delete independently.
Here is the respective Model and Code for the above example.
#include<iostream>
#include<string.h>
using namespace std;
class Department
{
char* name_p;
Notes Prepared By : Sarvagya Jain

public:

Department(char *dName)
{

name_p = new char(sizeof(strlen(dName)));


name_p = dName;
cout<<"Department Name "<<name_p<<"\n";
}
char* dName()
{
return(name_p);
}
~Department()
{
cout<<"Department Name Deleted \n";
delete(name_p);
}

};

class Student
{
char* name_p;

public:

Student(char *sName)
{

name_p = new char(sizeof(strlen(sName)));


name_p = sName;
cout<<"Student Name "<<name_p<<"\n";
}
char* sName()
{
return(name_p);
}
~Student()
{
cout<<"Student Name Deleted\n";
delete(name_p);
};
};
class Course
{
Notes Prepared By : Sarvagya Jain
Student * std_p;
Department * dept_p;
char * courseName_p;
static unsigned int index;
static Course *courseList[4];
public:

Course(char* crseName, Student* student, Department* dept):


courseName_p(0), std_p(student), dept_p(dept)
{
if (index < 4)
{
courseName_p = new char(sizeof(strlen(crseName)));
courseName_p = crseName;
//insert this Course in courseList
courseList[index] = this;
++index;
}
else
{
cout<<"Cannot accommodate any more Course\n";
}
cout<<"Course Name "<<courseName_p<<"\n";
};
~Course()
{
cout<<"Course Name Deleted \n";
delete (courseName_p);
};
static char* findStudent(char *crseName, char* deptName)
{
for(int i=0; i<index; i++)
{
if ( (courseList[i]->getCourseName() == crseName) &&(courseList[i]->getDeptName() ==
deptName) )
{
return(courseList[i]->getStdName());
}
}
}

char * getStdName()
{return(std_p->sName());};
char * getDeptName()
{return(dept_p->dName());};
char * getCourseName()
{return(courseName_p);};
Notes Prepared By : Sarvagya Jain
};

unsigned int Course::index =0;


Course* Course::courseList[4] = {0,0,0,0};
int main()
{
int i;

cout<<"\nExample of Association class...\n";


cout<<"-----------------------------------\n\n";
cout<<"We have got 4 students ...\n";
Student *studentNames[4] = {new Student("Meera"), new Student("Moina"), new
Student("Teena"), new Student("Mridula")} ;

cout<<"\n";

cout<<"We have got 2 Departments...\n";


Department *departNames[2] = {new Department("Mathemetics"), new
Department("ComputerSceince")} ;

cout<<"\n";

cout<<"Here class Course Associates Student and Department, with a Course name ...\n";
Course course1("DataStructure",studentNames[0], departNames[1]);
Course course2("Maths",studentNames[3], departNames[0]);
Course course3("Geometry",studentNames[2], departNames[0]);
Course course4("CA",studentNames[1], departNames[1]);
cout<<"\n";
cout<<"Finding a Student using Course and Department...\n";
cout<<"Student who has taken Maths Course in Mathematics Department
is:"<<Course::findStudent("Maths", "Mathemetics")<<endl;
cout<<"\n";
cout<<"Deletion of objects...\n\n";
for(i=0; i<4; ++i)
{
delete studentNames[i];
}
cout<<"\n";
for(i=0; i<2; ++i)
{
delete departNames[i];
}
cout<<"\n";
return(0);
}
output:
Example of Association class...
Notes Prepared By : Sarvagya Jain
-----------------------------------

We have got 4 students ...


Student Name Meera
Student Name Moina
Student Name Teena
Student Name Mridula

We have got 2 Departments...


Department Name Mathemetics
Department Name ComputerSceince

Here class Course Associates Student and Department, with a Course name ...
Course Name DataStructure
Course Name Maths
Course Name Geometry
Course Name CA

Finding a Student using Course and Department...


Student who has taken Maths Course in Mathematics Department is:Mridula

Deletion of objects...

Student Name Deleted


Segmentation fault

Aggregation in C++:
Aggregation in C++ (commonly called as a has-a relationship), is a process in which one class
defines a second class as an entity reference. It is a method of reusability of classes.
The concept of aggregation is based on real-world scenarios, which include many different classes
sharing a common attribute. For example, consider the class ‘address,’ along with a group of classes
of professions, like ‘student,’ ‘scientist,’ ‘programmer’ etc. Each of the objects of the classes would
have an attribute for their address. Hence, each class would contain an object of the ‘address’ class.
This, given below, is the basic concept’s usage.
#include<iostream>
using namespace std;
class address{
public:
string city, state, locality;
address( city_c, state_c, locality_c)
{ city = city_c; state = state_c; locality = locality_c; }
};

class student{
address*adrs;
public:
int id;
Notes Prepared By : Sarvagya Jain
string name;
student( int i, string nm, address*ad)
{ id = i; name = nm; adrs = ad; }
void display()
{ cout<<id<< " "<<name<< " "<<adrs->locality<< " "<<adrs->city<< " "<<adrs->state;}
};
void main()
{
address a1= address("C-146, Sec-15","Dmo","MP");
student s1 = student(101,"Nakul",&a1);
s1.display();
}
Output:
101 Nakul C-146, Sec-15 Dmo MP

File Handling In C++


Files are used to store data in a storage device permanently. File handling provides a mechanism to
store the output of a program in a file and to perform various operations on it.
A stream is an abstraction that represents a device on which operations of input and output are
performed. A stream can be represented as a source or destination of characters of indefinite length
depending on its usage.
In C++ we have a set of file handling methods. These include ifstream, ofstream, and fstream.
ofstream: This Stream class signifies the output file stream and is applied to create files for writing
information to files
ifstream: This Stream class signifies the input file stream and is applied for reading information
from files
fstream: This Stream class can be used for both read and write from/to files.
C++ provides us with the following operations in File Handling:
Creating a file: open()
Reading data: read()
Writing new data: write()
Closing a file: close()

Opening a File:
We can open a file using any one of the following methods:
1. First is bypassing the file name in the constructor at the time of object creation.
2. Second is using the open() function.
To open a file use
1 open() function
Syntax
1 void open(const char* file_name,ios::openmode mode);
Here, the first argument of the open function defines the name and format of the file with the
address of the file.
The second argument represents the mode in which the file has to be opened. The following modes
are used as per the requirements.
Modes Description
Notes Prepared By : Sarvagya Jain
in Opens the file to read(default for ifstream)

out Opens the file to write(default for ofstream)

binary Opens the file in binary mode

app Opens the file and appends all the outputs at


the end

ate Opens the file and moves the control to the


end of the file

trunc Removes the data in the existing file

nocreate Opens the file only if it already exists

noreplace Opens the file only if it does not already exist


Example
1 fstream new_file;
2 new_file.open(“newfile.txt”, ios::out);
Default Open Modes :
ifstream ios::in
ofstream ios::out
fstream ios::in | ios::out
Example of opening/creating a file using the open() function
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing file
}
return 0;
}
Example of Writing to a File
#include <iostream>
#include <fstream>
using namespace std;
int main()
Notes Prepared By : Sarvagya Jain
{
fstream new_file;
new_file.open("new_file_write.txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file<<"Learning File handling"; //Writing to file
new_file.close();
}
return 0;
}
Example of Reading from a File
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::in);
if(!new_file)
cout<<"No such file"; } else { char ch; while (!new_file.eof()) { new_file >>ch;
cout << ch;
}
new_file.close();
return 0;
}
Close a File
It is simply done with the help of the close() function.
Syntax: File Pointer.close()
Example
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::out);
new_file.close();
return 0;
}
Manipulators in C++
The manipulators in C++ are special functions that can be used with insertion (<<) and extraction
(>>) operators to manipulate or format the data in the desired way. Certain manipulators are used
Notes Prepared By : Sarvagya Jain
with << operator to display the output in a particular format, whereas certain manipulators are used
with >> operator to input the data in the desired form. The manipulators are used to set field widths,
set precision, inserting a new line, skipping white space etc.

Manipulator Purpose Header File

endl causes line feed to be inserted i.e. ‘\n’ iostream.h

dec,oct,hex set the desired number system iostream.h

setbase (b) output integers in base b iomanip.h

setw(w) read or write values to w characters iomanip.h

setfill (c) fills the whitespace with character c iomanip.h

setprecision(n) set floating point precision to n iomanip.h


Example dec, oct,hex manipulator.
#include<iostream>
using namespace std;
int main() {
int i;
cout<<"Enter hexadecimal number =";
cin>>hex>>i;
cout:<<"Hexadecimal value = "<<hex<<i<<endl;
cout<<"Octal Value = "<<oct<<i<<endl;
cout<<"Dcimal Value = "<<dec<<i<<endl;
return 0;
}
Output :
Enter hexadecimal = f
Hexadecimal = f
Octal value = 17
Decimal value = 15
Example setbase manipulator.
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int num;
cout<<"Enter number in Octal form = ";
cin>>setbase(8)>>num;
cout<<"Value of number in decimal form = "<<setbase(10)<<num<<endl;
cout<<"Value of number in octal form = "<<setbase(8)<<num<<endl;
cout<<"Value of number in hexadecimal form = "<<setbase(l6)<<num;
return 0;
}
Output
Notes Prepared By : Sarvagya Jain
Enter numberin Octal form = 21
Value of number in decimal fonn = 17
Value of number in octal fonn = 21
Value of number in hexadecimal fonn = 11
Example setw manipulator.
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int age = 22,rollno = 910l;
cout<<setw(l2)<<"My Rollno is"<<setw(8)<<rollno<<endl;
cout<<setw(l2)<<"My Aqe is"<<setw(8)<<age;
return 0;
}
Example setfill manipulator.
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int age = 22,rollno = 910l; cout<<setfill('#');
cout<<setw(4)<<age<<setw(6)<<rollno<<endl;
cout<<setw(6)<<age<<setw(8)<<rollno;

return 0;
}
Output :
##22##9101
####22####9101
Example setprecision manipulator.
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
float a = 129.455396;
cout<<setprecision(2)<<a<<endl;
cout<<setprecision(3)<<a;
return 0;
}
Output :
129.46
129.455

getline (string) in C++


The C++ getline() is a standard library function that is used to read a string or a line from an input
stream. It is a part of the <string> header. The getline() function extracts characters from the input
stream and appends it to the string object until the delimiting character is encountered.
1. Syntax:
Notes Prepared By : Sarvagya Jain
istream& getline(istream& is,string& str, char delim);
Parameters:
is: It is an object of istream class and tells the function about the stream from where to read the
input from.
str: It is a string object, the input is stored in this object after being read from the stream.
delim: It is the delimitation character which tells the function to stop reading further input after
reaching this character.
Example:
#include <iostream>
using namespace std;

int main () {
char name[20], address[25], about[50];

cout << "Enter your name: ";


cin.getline (name, 20);

cout << "Enter your City: ";


cin.getline (address, 25);

cout << "Enter your profession (press $ to complete): ";


cin.getline (about, 50, ‘$’); //$ is a delimiter

cout << "\n\nEntered details are:\n\n";


cout << "Name: " << name << endl;
cout << "Address: " << address << endl;
cout << "Profession is: " << about<< endl;
return 0;
}

2. Syntax:

istream& getline (istream& is, string& str);


The second declaration is almost the same as that of the first one. The only difference is, the latter
have an delimitation character which is by default newline(\n)character.
Parameters:
is: It is an object of istream class and tells the function about the stream from where to read the
input from.
str: It is a string object, the input is stored in this object after being read from the stream.
// C++ program to demonstrate getline() function
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Please enter your name: \n";
Notes Prepared By : Sarvagya Jain
getline(cin, str);
cout << "Hello, " << str<< " welcome !\n";

return 0;
}

get()
get() is used for accessing character arrays. It includes white space characters. Generally, cin with
an extraction operator (>>) terminates when whitespace is found. However, cin.get() reads a string
Syntax:
cin.get(string_name, size);
// C++ program to demonstrate cin.get()
#include <iostream>
using namespace std;
int main()
{
char name[25];
cin.get(name, 25);
cout<<name;
return 0;
}

You might also like