C++ Notes
C++ Notes
Identifiers:
C++ comes with libraries that help us in performing input/output. In C++ sequence of bytes
corresponding to input and output is commonly known as streams.
Input Stream: The direction of flow of bytes takes place from the input device (for ex Keyboard) to
the main memory.
Output Stream: The direction of flow of bytes takes place from the main memory to the output
device (for ex Display).
#include <iostream>
int main(){
OR
#include <iostream>
int main(){
NOTE:
#include <iostream>
int main() {
cout << "Enter two numbers: "; // “<<” is called Insertion Operator.
sum = n1 + n2;
return 0;
Header Files
Ex- #include “this.h”. This will produce an error if this.h is not present in the current directory.
Operators: Operators are the symbols that are used to perform pre-defined operations on variables
and operands.
1. Arithmetic Operators:
( + ) Addition: num1+num2
( - ) Subtraction: num1-num2
( * ) Multiplication: num1*num2
( / ) Division: num1/num2
( % ) Modulus: num2%num1
( ++ ) Increment: This is known as the increment operator and it increases the value of
operand by 1.
Pre-Increment: It first increment the value and later print. Ex: ++a
Post-Increment: It first print the value the value and later increment: Ex: a++
( -- )Decrement: This is known as the decrement operator and it decreases the value of
operand by 1.
Pre-Decrement: It first decrement the value and later print. Ex: --a
Post-Decrement: It first print the value and later decrement: Ex: a--
2. Relational Operators:
3. Logical Operators:
4. Assignment Operators:
5. Bitwise operators:
6. Miscellaneous Operators:
Unary Operators:
Unary operators need only one operand to perform operations like increment, decrement,
negation, etc.
Operator Precedence and Associativity
(Highest to Lowest)
Conditionals:
1. If statement
Syntax
if (condition){
statements;
2. If-else statement
Syntax
if (condition){
statement – 1;
else{
statement – 2;
3. If-else if statement
Syntax
if (condition - 1){
statement – 1;
statement – 2;
else{
statement – 3;
Conditional operators:
It is used when we want the condition to be true if both expressions are true.
Syntax
statement;
The first one (&) parses through all the conditions, despite their evaluation as true or false.
However, the (&&) traverses through the second condition only if the first condition is evaluated
as true, otherwise, it negates the entire condition.
It gives us a runtime error since 5 is divided by 0, which isn't a valid operation. However, if we
write-
we get “false” as the output. This is because our first condition is false, which is enough to make
the entire condition false here.
This operator is used when any one of the Boolean expressions is evaluated as true.
Syntax
if(condition - 1 || condition - 2){
statement;
|| -> logical or
The first one passes through all the conditions, despite their evaluation as true or false.
However, the ( || )traverses through the second condition only if the first condition is evaluated
as false, otherwise, it validates the entire condition.
It gives a runtime error since 5 is being divided by 0, which isn't a valid operation. However, if we
write-
We get “true” as the output. This is because our first condition is true, which is enough to make
the entire condition true in case of logical or.
It is a smaller version of the if-else statement. If the condition is true then statement - 1 is
executed else the
statement - 2 is executed.
Syntax
Switch statement
switch (expression){
case x:
// code
break;
case y:
// code
break;
default:
// code
Note: The case value must be literal or constant, and must be unique.
Loops
A while loop is a loop that runs through its body, known as a while statement, as long as a
predetermined is evaluated as true.
Syntax
while (condition)
Statement;
int i = 1;
i = i + 1;
For loop
Syntax:
statement
// logic
1)int index = 0;
}
3) for(int index = 0; index < 5; ) {
index = index + 1;
Syntax
do{
statement;
} while (condition);
do{
Output – 15
Break keyword
The break command allows you to terminate and exit a loop (do while/for / while) or switch
commands from any point other than the logical end.
Continue keyword
The continue keyword is used to end the current iteration in a for loop (or a while loop) and
continues to the next iteration.
It can be used in cases where we want the remaining block of code to get executed in the loop for
Functions
User-defined Functions
Standard Library Functions
Defining a Function
Parameters: Parameters actually act as variables inside the function. They are specified after the
Function name, inside the parentheses.
Function Prototype
Local Variable: Variables that are declared inside a function block and can be accessed/used
inside that specific function block only. They are unknown entities outside the function.
Global Variable: Variables that are declared outside all blocks or functions in a program
(generally at the top of the program) and can be accessed/used anywhere in the program (i.e.,
their reach is not limited to a block or function.
Formal parameters: Parameters that are defined during the function definition.
Actual parameters: Parameters that are passed during the function call in another function.
Constant parameter: Constant arguments are used when you don’t want your values to be
changed or modified by the function.
Pass by Value: The function parameter values (i.e., the value from the actual parameter) are
copied to another variable (formal parameter).
Example-
{
int ans = n1 + n2;
return ans;
int main(){
int a, b, ans;
cin>>a;
cin>>b;
cout<<("The sum of two numbers a and b is: ")<< ans << endl;
return 0;
Pass by Reference: Actual copy of the variable reference is passed to the function.
Example-
#include <iostream>
int temp=*a;
*a=*b;
*b=temp;
int main(){
swap(&x, &y);
return 0;
OR
#include <iostream>
int temp = a;
a = b;
b = temp;
int main(){
swap(num1, num2);
return 0;
data_type array_name[array_size];
OR
data_type array_name[array_size]={ele1,ele2,ele3,……}
OR
data_type array_name[]={ele1,ele2,ele3,……};
Structures:
The structure is a user-defined data type that is available in C++. Structures are used to combine
different types of data types.
Ex-
struct company{
string e_name;
int e_id;
float salary;
};
int main(){
struct company amazon;
amazon.e_name="Kashif";
amazon.e_id=25008;
amazon.salary=1245343;
cout<<amazon.e_name<<endl;
cout<<amazon.e_id<<endl;
cout<<amazon.salary<<endl;
return 0;
}
OR
int main(){
co amazon;
amazon.e_name="Kashif";
amazon.e_id=25008;
amazon.salary=1245343;
cout<<amazon.e_name<<endl;
cout<<amazon.e_id<<endl;
cout<<amazon.salary<<endl;
return 0;
}
Inline Function: Inline functions are used to reduce the function call.
When one function is being called multiple times in the program it increases the execution time,
so the inline function is used to reduce time and increase program efficiency.
Example-
return a*b;
int main(){
int a, b;
cin>>a>>b;
return 0;
When a function calls itself, it is called recursion and the function which is calling itself is called a
recursive function.
int main(){
int n;
cout<<"Enter the number: ";
cin>>n;
cout<<"The value of number is "<<factorial(n);
return 0;
}
Explanation:-
4 * factorial( 4-1 )
4 * 3 * factorial( 3-1 )
4* 3 * 2 * factorial( 2-1 )
4*3*2*1
Function Overloading
Function overloading is a process to make more than one function with the same name but
different parameters, numbers, or sequence.
Example-
int sum(int a, int b){ //If the datatype of a is mentioned as float, then it converts to float.
return a+b;
return a+b+c;
int main(){
return 0;
C++ language was designed with the main intention of adding object-
oriented programming to C language
As the size of the program increases readability, maintainability, and
bug-free nature of the program decrease.
This was the major problem with languages like C which relied upon
functions or procedure (hence the name procedural programming
language)
As a result, the possibility of not addressing the problem adequately was
high
Also, data was almost neglected, and data security was easily
compromised
Using classes solves this problem by modeling the program as a real-
world scenario
Classes: Classes are user-defined data types and are a template for creating objects. Classes
consist of variables and functions which are also called class members.
Public Access Modifier: All the variables and functions under the public access modifier will be
available to everyone. They can be accessed both inside and outside the class.
Dot(.) operator is used in the program to access public data members directly.
Private Access Modifier: All the variables and functions declared under a private access modifier
can only be used inside the class. They are not permissible to be used by any object or function
outside the class.
Example of Class-
class Employee{
private:
int a,b,c;
public:
int d,e;
void setData(int a1,int b1,int c1);
void getData(){
cout<<"The value of a is "<<a<<endl;
cout<<"The value of b is "<<b<<endl;
cout<<"The value of c is "<<c<<endl;
cout<<"The value of d is "<<d<<endl;
cout<<"The value of e is "<<e<<endl;
}
};
int main(){
Employee kashif;
kashif.d=6;
kashif.e=8;
kashif.setData(1,2,4);
kashif.getData();
return 0;
}
}
void getData(){
cout<<"The id is: "<<id<<" and emp no.:
"<<count<<endl;
}
static void getcount(){
cout<<"The value of count is "<<count<<endl;
}
};
Shivam.setData();
Shivam.getData();
Employee::getcount();
Pathak.setData();
Pathak.getData();
Employee::getcount();
return 0;
}
Friend Function:
Friend functions are those functions that have the right to access the private data
members of class even though they are not defined inside the class.
class complex{
int a,b;
public:
void set_num(int x,int y){
a=x;
b=y;
}
friend complex sum_complex(complex o1,complex o2);
void print_complex(){
cout<<a<<"+"<<b<<"i"<<endl;
}
};
int main(){
complex c1,c2, sum;
c1.set_num(1,2);
c1.print_complex();
c2.set_num(4,5);
c2.print_complex();
sum=sum_complex(c1,c2);
sum.print_complex();
return 0;
}
class Complex{
int a, b;
public:
// Creating a Constructor
Complex(); // Constructor declaration
void printNumber(){
cout << "Your number is " << a << " + " << b << "i" << endl;
}
};
public:
Complex(int, int); // Constructor declaration
void printNumber(){
cout << "Your number is " << a << " + " << b << "i" << endl;
}
};
Complex ::Complex(int x, int y) // ----> This is a parameterized constructor as it
takes 2 parameters
{
a = x;
b = y;
}
int main(){
// Implicit call
Complex a(4, 6);
a.printNumber();
// Explicit call
Complex b = Complex(5, 7);
b.printNumber();
return 0;
}
Constructor Overloading
Constructor overloading is a concept in which one class can have multiple
constructors with different parameters.
Example -
class complex{
int a,b;
public:
complex(){
a=0;
b=0;
}
complex(int x){
a=x;
b=0;
}
complex(int,int);
void print_complex(){
cout<<"The complex is "<<a<<'+'<<b<<'i'<<endl;
}
};
int main(){
complex a;
a.print_complex();
complex b(5);
b.print_complex();
complex c(8,9);
c.print_complex();
return 0;
}
class simple{
int data1, data2;
public:
simple(int x,int y=3){
data1=x;
data2=y;
}
void print_data();
};
int main(){
simple s(8);
s.print_data();
}
int main(){
simple s(8);
s.print_data();
}
Destructor
A destructor is a type of function which is called when the object is destroyed.
Destructor never takes an argument nor does it return any value.
Example-
int count=0;
class num{
public:
num(){
count++;
cout<<"This is the time when constructor is
called for object no. "<<count<<endl;
}
~num(){
cout<<"This is the time when destructor is
called for object no. "<<count<<endl;
count--;
}
};
int main(){
cout<<"Entering the main function"<<endl;
cout<<"Creating first object n1"<<endl;
num n1;
{
cout<<"Entering the block"<<endl;
cout<<"Creating two more objects"<<endl;
num n2, n3;
cout<<"Exiting the block"<<endl;
}
cout<<"Back to main"<<endl;
}
Output-
Entering the main function
Creating first object n1
This is the time when constructor is called for object no. 1
Entering the block
Creating two more objects
This is the time when constructor is called for object no. 2
This is the time when constructor is called for object no. 3
Exiting the block
This is the time when destructor is called for object no. 3
This is the time when destructor is called for object no. 2
Back to main
This is the time when destructor is called for object no. 1
File Handling:
There are two main operations which can be performed on files
Read File
Write File
File I/O: Reading and Writing Files
There are some useful classes for working with file in c++
fstreambase
ifstream derived from fstreambase
ofstream derived from fstreambase
In order to work with files in C++, you will have to open it. Primarily, there are 2 ways to open a
file:
int main(){
string st = "Harry bhai";
// Opening files using constructor and writing it
ofstream out("sample60.txt"); // Write operation
out<<st;
string st2;
// Opening files using constructor and reading it
in>>st2;
getline(in,st2);
cout<<st2;
return 0;
}
Example-
Using the member function to open
#include <iostream>
#include <fstream>
using namespace std;
int main(){
// declaring an object of the type ofstream
ofstream out;
//connecting the object out to the text file using the member function
out.open("sample60.txt");
//writing to the file
out <<"This is me\n";
out <<"This is also me";
//closing the file connection
out.close();
return 0;
}
Exception Handling: It is a process to handle runtime errors. We perform
exception handling. So, the normal flow of the program can be maintained even
after runtime errors.
Syntax:
try{
throw exception;
}
catch(return_type variable){
//code
}
try: It is representing block of code that can throw an exception.
catch: It is representing block of code that is executed when a particular exception
is thrown.
throw: It is used to throw an exception.
Example-
int main(){
int a,b,c;
cout<<"Enter first no.: ";
cin>>a;
cout<<"Enter second no.: ";
cin>>b;
try{
if (b==0){
throw b;
}
else{
c=a/b;
cout<<c<<endl;
}
}
catch(int x){
cout<<"Can't divide by "<<x;
}
return 0;
}