C++ Notes

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

Variable:

A variable is the title of a reserved region allocated in memory.

Creating Variables Example:

Naming Conventions for variables in C++:

 Variable names should not begin with a number.


 Whitespaces are not permitted in variable names.
 A C++ keyword (reserved word) cannot be used as a variable name.
 Variable must begin with a letter or an underscore (_)
 Variable cannot contain whitespaces or special characters like !, #, %, etc.
 Variable can contain letters, digits, and underscores.

Identifiers:

Identifier is a name given to a package, class, interface, method, or variable.

C++ Data Types:

C++ Input/Output Program in C++:

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>

using namespace std;

int main(){

cout << "Hello World in C++";

OR

#include <iostream>

using namespace std;

int main(){

printf("Hello World in C++");

NOTE:

printf() can only be used print string.

Taking input from the user:

#include <iostream>

using namespace std;

int main() {

int n1, n2, sum;

cout << "Enter two numbers: "; // “<<” is called Insertion Operator.

cin >> n1 >> n2; //”>>” is called Extraction Operator.

sum = n1 + n2;

cout << sum <<endl;

return 0;

Header Files

There are two types of header files:

1. System header files: It comes with the compiler. Ex - #include <iostream>

2. User-defined header files: It is written by the programmer.

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.

Operators in C++ can be classified into 6 types:

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:

 sizeof :: For example, sizeof(p), where ‘p’ is integer, will return 4.


 Condition ? Expression1 : Expression2 :: Conditional operator (?). If Condition is true then it
returns the value of Expression1 otherwise it returns the value of Expression2.
 , :: Comma operator is a binary operator.
 . (dot) and -> (arrow) :: Member operators are used to reference individual members of
classes, structures, and unions. The dot operator is used for the actual object. The arrow
operator is used with a pointer to an object.
 Cast :: Casting operators convert one data type to another. For example, int(4.3000) would
return 4 (i.e. a float number here is converted into int).
 & :: Address-of operator & returns the memory address of a variable. For example &p; will
give the actual memory address of the variable p.
 * :: Pointer operator * points to a variable. For example *p; will point to the variable p.

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;

else if (condition - 2){

statement – 2;

else{

statement – 3;

Conditional operators:

a. Logical-and operator (&&)

It is used when we want the condition to be true if both expressions are true.

Syntax

if (condition - 1 && condition - 2){

statement;

Common misconception: ‘&’ v/s ‘&&’

& -> compares bitwise

&& -> logical

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.

cout << (false & 5/0==2);

It gives us a runtime error since 5 is divided by 0, which isn't a valid operation. However, if we
write-

cout << (false && 5/0==2);

we get “false” as the output. This is because our first condition is false, which is enough to make
the entire condition false here.

Tip: Always use parentheses around every condition.

b. Logical-or operator (||)

This operator is used when any one of the Boolean expressions is evaluated as true.

Syntax
if(condition - 1 || condition - 2){

statement;

Common misconception: ‘|’ v/s ‘||’

| -> compares bitwise

|| -> 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.

cout << (true | 5/0==2);

It gives a runtime error since 5 is being divided by 0, which isn't a valid operation. However, if we
write-

cout << (true || 5/0==2);

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.

Ternary operator (?:)

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

condition? statement - 1 : statement - 2;

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 loop is a sequence of instructions continually repeated until a certain condition is reached.

We have the following types of iterative statements-

1. The while loop

2. The for loop

3. The do-while loop

The while loop

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;

Ex: Print the first 10 natural numbers.

int i = 1;

while (i <= 10){

cout << i << “ “;

i = i + 1;

For loop

Syntax:

for (init-statement; condition; final-expression){

statement

// logic

Omitting parts of for loop

1)int index = 0;

for(; index < 5; index++)

cout << index << “ “;

2) for(int index = 0; ; index++) {

statement + code inside the loop must stop the iteration!

}
3) for(int index = 0; index < 5; ) {

cout << index << “ “;

index = index + 1;

The do-while loop

Syntax

do{

statement;

} while (condition);

Let us understand it with the help of the following example:

int idx = 15;

do{

cout << idx << “ “;

} while (idx < 5);

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

the specific iteration.

Functions

A function is a block of code or collection of statements or a set of codes grouped together to


perform a certain task or operation.

 User-defined Functions
 Standard Library Functions

How to declare Functions:

Defining a Function

return_type function_name(parameter1, parameter2, .........) {


statements;

Parameters: Parameters actually act as variables inside the function. They are specified after the
Function name, inside the parentheses.

Function Prototype

The function prototype is declared before the main().

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.

Default parameter: A default argument is a value in the function declaration assigned


automatically by the compiler if the calling function does not pass any value to that argument.

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).

This is also known as ‘call by value’.

Example-

int add (int n1, int n2) //formal parameters

{
int ans = n1 + n2;

return ans;

int main(){

int a, b, ans;

cout<<("Enter the first number: ")<< endl;

cin>>a;

cout<<("Enter the second number: ")<< endl;

cin>>b;

ans = add(a, b); //actual parameters

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.

This is also known as ‘call by reference’.

Example-

//Call by reference using pointer.

#include <iostream>

using namespace std;

void swap(int * a, int * b){

int temp=*a;

*a=*b;

*b=temp;

int main(){

int x=4, y=5;

cout << "Before swap: " << endl;

cout <<x <<" "<< y << endl;

swap(&x, &y);

cout << "After swap: " << endl


cout << x <<" "<< y << endl

return 0;

OR

//Call by reference using reference variables

#include <iostream>

using namespace std;

void swap(int &a, int &b){

int temp = a;

a = b;

b = temp;

int main(){

int num1 = 20;

int num2 = 32;

cout << "Before swap: " << "\n";

cout << num1 <<" "<< num2 << "\n";

swap(num1, num2);

cout << "After swap: " << "\n";

cout << num1 <<" "<< num2 << "\n";

return 0;

Array Declaration and Creation

Syntax for creating a new array in C++ is:-

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

typedef struct company{


string e_name;
int e_id;
float salary;
}co;

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-

inline int product(int a, int b){

return a*b;

int main(){

int a, b;

cout<<"Enter the value of a and b"<<endl;

cin>>a>>b;

cout<<"The product of a and b is "<<product(a,b)<<endl;

return 0;

Recursion and Recursive Function

When a function calls itself, it is called recursion and the function which is calling itself is called a
recursive function.

int factorial(int n){


if (n<=1){
return 1;
}
return n*factorial(n-1);
}

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.

cout<<"Using function with 2 arguments"<<endl;

return a+b;

int sum(int a, int b, int c){

cout<<"Using function with 3 arguments"<<endl;

return a+b+c;

int main(){

cout<<"The sum of 3 and 6 is "<<sum(3,6)<<endl;

cout<<"The sum of 3, 7 and 6 is "<<sum(3, 7, 6)<<endl;

return 0;

Why Object-Oriented Programming?

 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

Difference between Procedure Oriented Programming and Object-Oriented


Programming
Procedure Oriented Programming

 Consists of writing a set of instructions for the computer to follow


 The main focus is on functions and not on the flow of data
 Functions can either use local or global data
 Data moves openly from function to function
Object-Oriented Programming

 Works on the concept of classes and object


 A class is a template to create objects
 Treats data as a critical element
 Decomposes the problem in objects and builds data and functions around
the objects

Basic Concepts in Object-Oriented Programming

 Classes - Basic template for creating objects


 Objects – Basic run-time entities
 Data Abstraction & Encapsulation – Wrapping data and functions into
a single unit
 Inheritance – Properties of one class can be inherited into others
 Polymorphism – Ability to take more than one forms
 Dynamic Binding – The code which will execute is not known until the
program runs
 Message Passing – message (Information) call format

Benefits of Object-Oriented Programming

 Better code reusability using objects and inheritance


 Principle of data hiding helps build secure systems
 Multiple Objects can co-exist without any interference
 Software complexity can be easily managed

We use classes instead of structure because in structure:


 Everything is public and can be accessed easily.
 We cannot add functions to it.

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;
}
};

void Employee :: setData(int a1,int b1,int c1){


a=a1;
b=b1;
c=c1;
}

int main(){
Employee kashif;
kashif.d=6;
kashif.e=8;
kashif.setData(1,2,4);
kashif.getData();
return 0;
}

Static Data Members:


When a static data member is created, there is only a single copy of the data
member which is shared between all the objects of the class.
Example –
class Employee{
int id;
static int count;
public:
void setData(){
cout<<"Enter ID: ";
cin>>id;
count++;

}
void getData(){
cout<<"The id is: "<<id<<" and emp no.:
"<<count<<endl;

}
static void getcount(){
cout<<"The value of count is "<<count<<endl;
}
};

int Employee :: count;


int main(){
Employee Kashif,Shivam,Pathak;
Kashif.setData();
Kashif.getData();
Employee::getcount();

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;
}
};

complex sum_complex(complex o1,complex o2){


complex o3;
o3.set_num((o1.a+o2.a),(o1.b+o2.b));
return o3;
}

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;
}

Properties of friend functions:


1. Not in the scope of class
2. since it is not in the scope of the class, it cannot be called from the object of
that class. c1.sumComplex() == Invalid
3. Can be invoked without the help of any object
4. Usually contains the objects as arguments
5. Can be declared inside public or private section of the class
6. It cannot access the members directly by their names and need
object_name.member_name to access any member.
Constructors
A constructor is a special member function with the same name as the class. The
constructor doesn’t have a return type. Constructors are used to initialize the
objects of its class. Constructors are automatically invoked whenever an object
is created.
Example –
#include <iostream>
using namespace std;

class Complex{
int a, b;

public:
// Creating a Constructor
Complex(); // Constructor declaration

void printNumber(){
cout << "Your number is " << a << " + " << b << "i" << endl;
}
};

Complex ::Complex() // ----> This is a default constructor as it takes no


parameters.
{
a = 10;
b = 15;
}
int main(){
Complex c1, c2, c3;
c1.printNumber();
c2.printNumber();
c3.printNumber();
return 0;
}
Characteristics of Constructors:
A constructor should be declared in the public section of the class.
They are automatically invoked whenever the object is created.
They cannot return values and do not have return types.
It can have default arguments.
We cannot refer to their address.
Parameterized Constructor: Parameterized constructors are those constructors
that take one or more parameters.
Default Constructor: Default constructors are those constructors that take no
parameters.
Example-
#include<iostream>
using namespace std;
class Complex{
int a, b;

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;
}
};

complex::complex(int x,int y){


a=x;
b=y;
}

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();
};

void simple :: print_data(){


cout<<"The value of data1 and data2 is "<<data1<<" and
"<<data2;
}

int main(){
simple s(8);
s.print_data();
}

Constructors with Default Arguments


Default arguments of the constructor are those which are provided in the
constructor declaration.
Example-
class simple{
int data1, data2;
public:
simple(int x,int y=3){
data1=x;
data2=y;
}
void print_data();
};

void simple :: print_data(){


cout<<"The value of data1 and data2 is "<<data1<<" and
"<<data2;
}

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:

 Using the constructor


 Using the member function open() of the class
Example-
Using constructor to open
#include<iostream>
#include<fstream>
using namespace std;

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;
}

Polymorphism: It is something that has several forms.


There are two types of polymorphism:
1. Compile Time Polymorphism:
In compile-time polymorphism, it is already known which function will run.
Compile-time polymorphism is also called early binding, which means that you
are already bound to the function call.
 Function Overloading
 Operator Overloading
2. Run Time Polymorphism:
In the run-time polymorphism, the compiler doesn’t know already what will
happen at run time. Run time polymorphism is also called late binding.
Virtual Function

You might also like