OOPS
OOPS
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
* multiplication
/ division
== Equal to 5 == 3 is evaluated to 0
= 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
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
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.
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);
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
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.
}
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.
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;
}
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.
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.
Adding new data and functions is not easy. Adding new data and functions is easy.
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
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.
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;
}
// 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;
}
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;
function_name(object_name);
Returning Object as argument
Syntax:
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
#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
private:
Notes Prepared By: Sarvagya Jain
int numA;
public:
// constructor to initialize numA to 12
ClassA() { numA=12;}
};
class ClassB {
private:
int numB;
public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}
// 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) {
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
};
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.
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:
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;
};
int main()
{
Student s1,s2;
s1.getHeight(5,10);
s2.getHeight(6,1);
return 0;
}
Output –
Student 2 is taller
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;
}
int main() {
Distance D1(11, 10), D2(5, 11);
return 0;
}
Output:
First Distance : F: 11 I:10
Second Distance :F: 5 I:11
First Distance :F: 5 I:11
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;
}
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.
// 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
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;
}
};
};
// 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
};
// 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
void main()
{
ClassD obj;
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;
};
void main()
{
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
}
Output:
A : 100
B : 20
Notes Prepared By : Sarvagya Jain
C : 30
D : 40
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
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
}
}
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)
{
};
class Student
{
char* name_p;
public:
Student(char *sName)
{
char * getStdName()
{return(std_p->sName());};
char * getDeptName()
{return(dept_p->dName());};
char * getCourseName()
{return(courseName_p);};
Notes Prepared By : Sarvagya Jain
};
cout<<"\n";
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
-----------------------------------
Here class Course Associates Student and Department, with a Course name ...
Course Name DataStructure
Course Name Maths
Course Name Geometry
Course Name CA
Deletion of objects...
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
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)
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
int main () {
char name[20], address[25], about[50];
2. Syntax:
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;
}