C++ Study Material (UNIT I & II)
C++ Study Material (UNIT I & II)
UNIT - I
Introduction
C++ is a powerful and versatile programming language that was developed as an extension of the C
programming language. It was created by Bjarne Stroustrup in the early 1980s at Bell Labs. C++ is widely
used for developing system software, game development, embedded systems, and various applications
where high-performance and efficient programming are essential.
The advantages:
➢ Conciseness: programming languages allow us to express common sequences of commands more
concisely. C++ provides some especially powerful shorthands.
➢ Maintainability: modifying code is easier when it entails just a few text edits, instead of
rearranging hundreds of processor instructions. C++ is object oriented which further improves
maintainability.
➢ Portability: different processors make different instructions available. Programs writ- ten as text
can be translated into instructions for many different processors; one of C++’s strengths is that it
can be used to write programs for nearly any processor.
C++ is a high-level language: when you write a program in it, the shorthands are sufficiently expressive
that you don’t need to worry about the details of processor instructions. C++ does give access to some
lower-level functionality than other languages (e.g. memory addresses).
The Compilation Process
A program goes from text files (or source files) to processor instructions as follows:
Object files are intermediate files that represent an incomplete copy of the program: each source
file only expresses a piece of the program, so when it is compiled into an object file, the object file has
some markers indicating which missing pieces it depends on. The linker takes those object files and the
compiled libraries of predefined code that they rely on, fills in all the gaps, and spits out the final program,
which can then be run by the operating system (OS).
The compiler and linker are just regular programs. The step in the compilation process in which the
compiler reads the file is called parsing. In C++, all these steps are performed ahead of time, before you
start running a program. In some languages, they are done during the execution process, which takes time.
This is one of the reasons C++ code runs far faster than code in many more recent languages.
C++ actually adds an extra step to the compilation process: the code is run through a preprocessor,
which applies some modifications to the source code, before being fed to the compiler. Thus, the modified
diagram is:
1
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
Tokens
Tokens are the minimal chunk of program that have meaning to the compiler – the smallest
meaningful symbols in the language. Our code displays all 6 kinds of tokens, though the usual use of
operators is not present here:
Keywords Words with special meaning to the int, double, for, auto
compiler
Identifiers Names of things that are not built into cout, std, x, myFunction
the language
Literals Basic constant values whose value is "Hello, world!”, 24.3,0, ‘c’
specified directly in the source code
Whitespace Spaces of various sorts; ig- nored by Spaces, tabs, newlines, comments
the compiler
Operators
➢ Arithmetic Operators
➢ Relational Operators
➢ Logical Operators
➢ Bitwise Operators
➢ Assignment Operators
Arithmetic Operators
➢ Addition Operator (+): It is used to add two operands. Suppose X and Y are two operands, this
plus operators will add up these two operands X + Y.
➢ Subtraction Operator (-): It is used to subtract two operands. Suppose X and Y are two operands,
then this minis operator will subtract the value of the second operand from the first operand.
➢ Multiplication Operator (*): It is used to multiply two operands. Suppose X and Y are two
operands then this multiplication operator will multiply X with Y.
2
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
➢ Division Operator (/): It is used to numerator by the denominator. Suppose X and Y are two
operands, this division operator divides the numerator by denominator.
➢ Modulus Operator (%): It is used to give the remainder of the division. Suppose X and Y are two
operands then this modulus operator first divides the numerator by denominator and gives the
remainder.
➢ Increment Operator (++): It is used to increment the value of the variable by 1. Suppose X is the
operand, then this increment operator will add the value of X by 1.
➢ Decrement Operator (–): It is used to decrementing the value of the variable by 1. Suppose X is
the operand, this decrement operator will decrement the value of X by 1.
▪ int a = 10, b = 3;
▪ int sum = a + b; // 13
▪ int difference = a - b; // 7
▪ int product = a * b; // 30
▪ int quotient = a / b; // 3
▪ int remainder = a % b; // 1
Relational Operators
Conditionals use two kinds of special operators: relational and logical. These are used to determine
whether some condition is true or false. The relational operators are used to test a relation between two
expressions.
Example:
▪ int x = 5, y = 10;
▪ bool isEqual = (x == y); // false
▪ bool isNotEqual = (x != y); // true
▪ bool isLessThan = (x < y); // true
Logical Operators
The logical operators are often used to combine relational expressions into more complicated Boolean
expressions:
3
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
The operators return true or false, according to the rules of logic:
The! operator is a unary operator, taking only one argument and negating its value:
Boolean variables can be used directly in these expressions, since they hold true and false values.
In fact, any kind of value can be used in a Boolean expression due to a quirk C++ has: false is represented
by a value of 0 and anything that is not 0 is true. So, “Hello, world!” is true, 2 is true, and any int variable
holding a non-zero value is true. This means !x returns false and x && y returns true!
Bitwise Operators
1. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two
numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) in C 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) in C 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) in C takes two numbers, the left shifts the bits of the first operand, and the
second operand decides the number of places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and the
second operand decides the number of places to shift.
4
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
Example
// C++ Program to demonstrate
// Bitwise Operator
#include <iostream>
using namespace std;
// Main function
int main()
{
int a = 5; // 101
int b = 3; // 011
// Bitwise AND
int bitwise_and = a & b;
// Bitwise OR
int bitwise_or = a | b;
// Bitwise XOR
int bitwise_xor = a ^ b;
// Bitwise NOT
int bitwise_not = ~a;
5
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
// Printing the Results of
// Bitwise Operators
cout << "AND: " << bitwise_and << endl;
cout << "OR: " << bitwise_or << endl;
cout << "XOR: " << bitwise_xor << endl;
cout << "NOT a: " << bitwise_not << endl;
cout << "Left Shift: " << left_shift << endl;
cout << "Right Shift: " << right_shift << endl;
getch();
}
Output
AND: 1
OR: 7
XOR: 6
NOT a: -6
Left Shift: 20
Right Shift: 2
Assignment Operators
Assignment operators are used to assign values to variables.
we use the assignment operator (=) to assign the value 10 to a variable called x:
Example : int x = 10;
Data types in C++
C++ supports the following data types:
1. Primary or Built-in or Fundamental data type
2. Derived data types
3. User-defined data types
6
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
Primitive Data Types
• Integer: The keyword used for integer data types is int. Integers typically require 4 bytes of
memory space and range from -2147483648 to 2147483647.
• Character: Character data type is used for storing characters. The keyword used for the character
data type is char. Characters typically require 1 byte of memory space and range from -128 to 127
or 0 to 255.
• Boolean: Boolean data type is used for storing Boolean or logical values. A Boolean variable can
store either true or false. The keyword used for the Boolean data type is bool.
• Floating Point: Floating Point data type is used for storing single-precision floating-point values
or decimal values. The keyword used for the floating-point data type is float. Float variables
typically require 4 bytes of memory space.
• Double Floating Point: Double Floating Point data type is used for storing double-precision
floating-point values or decimal values. The keyword used for the double floating-point data type
is double. Double variables typically require 8 bytes of memory space.
• void: Void means without any value. void data type represents a valueless entity. A void data type
is used for those function which does not return a value.
• Wide Character: Wide character data type is also a character data type but this data type has a
size greater than the normal 8-bit data type. Represented by wchar_t. It is generally 2 or 4 bytes
long.
• sizeof() operator: sizeof() operator is used to find the number of bytes occupied by a variable/data
type in computer memory.
User-Defined Data Types
The data types that are defined by the user are called the derived datatype or user-defined derived data
type. These types include:
• Class
• Structure
• Union
• Enumeration
7
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
• Typedef
The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data
Types. These can be of four types namely:
• Function
• Array
• Pointers
• References
Expression
C++ expression consists of operators, constants, and variables which are arranged
according to the rules of the language. It can also contain function calls which return values. An
expression can consist of one or more operands, zero or more operators to compute a value.
Every expression produces some value which is assigned to the variable with the help of an
assignment operator.
1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c
4. (a+b) * (x+y)
An expression can be of following types:
o Constant expressions
o Integral expressions
o Float expressions
o Pointer expressions
o Relational expressions
o Logical expressions
o Bitwise expressions
o Special assignment expressions
Control Structures
Decision making statements: C++ language supports the decision making-statements as listed
below.
➢ The if statement
➢ The if-else statement
➢ The nested if-else statements.
➢ The else-if ladder
8
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
➢ The switch case statement.
➢ The break statements
The decision-making statement checks the given condition and then executes its subblock. The decision
statement decides the statement to be executed after the success or failure of
a given condition.
The if Statement: C++ uses the keyword if to execute a set of command lines or a command line when
the logical condition is true. It has only one option. The syntax for the simplest if statement is as shown
in figure.
The if Statement: C++ uses the keyword if to execute a set of command lines or a command line when the
logical condition is true. It has only one option. The syntax for the simplest if statement is as shown in
figure.
Example
#include<iostream>
using namespace std;
int main()
{
int price;
cout<<“\nEnter the price of the book:”;
cin>>price;
if(price<=600) {
cout<<“\n Hurry up buy the book!!!!!”; }
return 0;
}
Output:
Enter the price of the book: 345
Hurry up buy the book!!!!!
Multiple Ifs: The syntax of multiple ifs is shown in figure. Programs on multiple ifs are as
follows.
if (expression) /* no semi-colon */
Statement 1;
9
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
if (expression) /* no semi-colon */
Statement 2;
if (expression) /* no semi-colon */
Statement 3;
/* Write a program to enter the percentage of marks obtained by a student and display the class
obtained.*/
#include<iostream> using
namespace std; int main()
{
float per;
cout<<“\nEnter the percentage:”;
cin>>per;
if(per>=90 && per<=100)
cout<<“\nDistinction”;
if(per>=70 && per<90)
cout<<“\nFirst class”;
if(per>=50 && per<70)
cout<<“\nSecond class”;
if(per>=40 && per<50)
cout<<“\nPass”;
if(per<40)
cout<<“\nFail”;
return 0;
}
Output:
Enter the percentage: 95
Distinction.
The if-else Statement: In the if–else statement, if the expression/condition is true, the body of the if
statement is executed; otherwise, the body of the else statement is executed.
Example
#include<iostream> using
namespace std; int main()
{
int age;
10
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
cout<<“Enter Your Age:”;
cin>>age;
if (age>=18) {
cout<<“You are eligible for voting.”; }
else {
cout<<“You are not eligible for voting”<<endl;
cout<< “Wait for”<<18-age<<“year(s).”;
}
return 0;
}
Output:
Enter Your Age: 17
You are not eligible for voting Wait
for 1 year(s).
Nested if-else Statements: In this kind of statement, a number of logical conditions are tested for taking
decisions. Here, the if keyword followed by an expression is evaluated. If it is true, the compiler e xecutes
the block following the if condition; otherwise, it skips this block and executes the else block. It uses
the if statement nested inside an if-else statement, which is nested inside another if-else statement. This
kind of nesting can be limitless.
Example
#include<iostream> using
namespace std; int main()
{
int a,b,c;
cout<<“\nEnter three numbers:”;
cin>>a>>b>>c;
if(a>b) {
11
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
if(a>c)
cout<<“\n a is largest ”; else
cout<<“\n c is largest ”; }
else {
if(b>c)
cout<<“\n b is largest ”; else
cout<<“\n c is largest ”; }
return 0; }
Output:
Enter three numbers: 3 6 89 c is
largest.
The else-if Ladder: A common programming construct is the else-if ladder, sometimes called the if-else-if
staircase because of its appearance. In the program one can write a ladder of else-if. The program goes
down the ladder of else-if, in anticipation of one of the expressions being true.
Example:
#include<iostream> using
namespace std;
int main()
{
int previous,current,consumed; float
total;
clrscr();
cout<<“\nInitial & Final Readings:”;
cin>>previous>>current;
12
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
consumed = current-previous;
if(consumed>=200 && consumed<=500)
total=consumed *3.50;
else if(consumed>=100 && consumed<=199)
total=consumed *2.50;
else if(consumed<100)
total=consumed*1.50;
cout<<“\n Total no of units consumed: ”<<consumed; cout<<“\n
Electric Bill for units ”<< consumed<< “is” <<total; return 0;
}
Output:
Initial & final readings: 100 235 Total
no of units consumed: 135 Electric bill
for units 135 is 337.5
Syntax:
goto label;
..
.
label: statement;
Flow diagram
13
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
void main()
{
int x;
cout<<“Enter a Number:”;
cin>>x;
if (x%2==0)
goto even; else
goto odd; even:
cout<<x<<“ is an Even Number.”;
return;
odd:
cout<<x<<“ is an Odd Number.”;
}
The break Statement: The break statement allows the programmer to terminate the loop. The break
skips from the loop or the block in which it is defined.
Syntax Flow Diagram
Example
// C++ program to illustrate
// using break statement
// in Nested loops
#include <iostream>
using namespace std;
int main()
{
14
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
for (int j = 1; j <= 10; j++) {
if (j > 3)
break; Output
else ***
cout << "*";
***
}
cout << endl; ***
}
***
return 0; ***
}
15
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
UNIT -II
Functions
Functions in C++ play a crucial role in organizing code, promoting reusability, and improving the
overall structure of a program. A function is a block of code that performs a specific task and can be
called from other parts of the program. In C++, functions are declared and defined with a specific
syntax.
• Functions make code modular. Consider a big file having many lines of code. It becomes really
simple to read and use the code, if the code is divided into functions.
• Functions provide abstraction. For example, we can use library functions without worrying
about their internal work.
Function Declaration
• Return Type: Specifies the type of data that the function will return. If a function doesn't return
any value, you can use void as the returnType.
• Function Name: The name of the function, which should be unique within the scope of the
program.
• parameters: Input values that the function expects. These are optional; a function may have no
parameters.
A function declaration tells the compiler about the number of parameters, data types of
parameters, and returns type of function. Writing parameter names in the function declaration is
optional but it is necessary to put them in the definition. Below is an example of function
declarations. (parameter names are not present in the below declarations)
After declaring a function, you need to provide its definition, which includes the actual
implementation of the code. The function definition follows the declaration and typically appears
outside the main function:
// You can use the parameters and perform the desired operations
// Optionally, return a value using the return statement if the returnType is not void
Example
int add(int a, int b) {
return a + b;
}
Function Call:
To use a function, you need to call it from another part of your program. The syntax for calling a
function is:
In this example, add(5, 3) is called, and the result is assigned to the variable sum, which is then printed
to the console.
Types of Functions
User-defined functions are user/customer-defined blocks of code specially customized to reduce the
complexity of big programs. They are also commonly known as “tailor-made functions” which are built
only to satisfy the condition in which the user is facing issues meanwhile reducing the complexity of the
whole program.
Library Function
Library functions are also called “built-in Functions”. These functions are part of a compiler package
that is already defined and consists of a special function with special and different meanings. Built-in
Function gives us an edge as we can directly use them without defining them whereas in the user-defined
function we have to declare and define a function before using them.
For Example: sqrt(), setw(), strcat(), etc.
The parameters passed to the function are called actual parameters. For example, in the program below,
5 and 10 are actual parameters.
The parameters received by the function are called formal parameters. For example, in the above program
x and y are formal parameters.
18
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
Formal Parameter and Actual Parameter
1. Pass by Value: In this parameter passing method, values of actual parameters are copied to the
function’s formal parameters. The actual and formal parameters are stored in different memory
locations so any changes made in the functions are not reflected in the actual parameters of the
caller.
2. Pass by Reference: Both actual and formal parameters refer to the same locations, so any changes
made inside the function are reflected in the actual parameters of the caller.
Difference between call by value and call by reference
A copy of the value is passed to the function An address of value is passed to the function
Changes made inside the function are not Changes made inside the function are reflected
reflected on other functions outside the function as well
Actual and formal arguments will be created at Actual and formal arguments will be created at
different memory location same memory location.
19
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
Function Types Diagram Representation
20
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
Characteristics of Friend function
➢ A global function or a member function of another class, both can be declared as a friend
function.
➢ A friend function in C++ should not be in the scope of the class of which it is supposed to be the
friend. This means that the function which is declared as a friend should not be a member of
the same class.
➢ A friend function in C++ can be declared anywhere in the class, that is, in the public section or
the private section of the class.
➢ The friend function in C++ can be called (invoked) just like a normal function using any instance
of any class (object).
➢ A friend function in C++ cannot directly access the protected or private data members of the
class. It is required to use an object (instance of that class) and then use the dot operator (.) to
access the data members.
➢ Friend functionality in C++ is not restricted to only one class. That is, it can be a friend to many
classes.
➢ Friend functions in C++ can use objects (instance of a class) as arguments.
C++ Recursion
When function is called within the same function, it is known as recursion in C++. The function
which calls the same function, is known as recursive function.
A function that calls itself, and doesn’t perform any task after function call, is known as tail
recursion. In tail recursion, we generally call the same function with return statement.
Recursion in C++ refers to a function calling itself during its execution. Recursive functions solve
problems in smaller, more manageable parts, often reducing complex tasks into simpler subproblems.
When using recursion, it's crucial to define a base case that stops the recursive calls and prevents infinite
looping.
recursionfunction()
{
recursionfunction(); // calling self function
}
Example
#include <iostream>
// Recursive function to calculate factorial
int factorial(int n) {
// Base case
if (n <= 1) {
21
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
return 1;
}
// Recursive case
else {
return n * factorial(n - 1);
}
}
int main() {
// Example usage
int num = 5;
std::cout << "Factorial of " << num << " is: " << factorial(num) << std::endl;
return 0;
}
Inline Function
C++ provides inline functions to reduce the function call overhead. An inline function is a function that
is expanded in line when it is called. When the inline function is called whole code of the inline function
gets inserted or substituted at the point of the inline function call. This substitution is performed by the
C++ compiler at compile time. An inline function may increase efficiency if it is small.
Syntax:
inline return-type function-name(parameters)
{
// function code
}
22
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
Example:
#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
Inline functions Advantages:
1. Function call overhead doesn’t occur.
2. It also saves the overhead of push/pop variables on the stack when a function is called.
3. It also saves the overhead of a return call from a function.
4. When you inline a function, you may enable the compiler to perform context-specific
optimization on the body of the function. Such optimizations are not possible for normal
function calls. Other optimizations can be obtained by considering the flows of the calling
context and the called context.
5. An inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function called preamble and return.
Virtual Function
A virtual function (also known as virtual methods) is a member function that 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 method.
• Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for the function call.
• They are mainly used to achieve Runtime polymorphism.
• Functions are declared with a virtual keyword in a base class.
• The resolving of a function call is done at runtime.
23
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
Rules for Virtual Functions
The rules for the virtual functions in C++ are as follows:
1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using a pointer or reference of base class type to achieve
runtime polymorphism.
4. The prototype of virtual functions should be the same in the base as well as the derived class.
5. 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.
6. A class may have a virtual destructor but it cannot have a virtual constructor.
// C++ program to illustrate
// concept of Virtual Functions
#include <iostream>
using namespace std;
class base {
public:
virtual void print() { cout << "print base class\n"; }
void show() { cout << "show base class\n"; }
};
class derived : public base {
24
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)
public:
void print() { cout << "print derived class\n"; }
25
Prepared by Mrs. V. Backiyalakshmi M.S{IT&M}., M.Phil., NET., (P.hD)