0% found this document useful (0 votes)
13 views104 pages

C

comprehensive notes of C ++ programming language

Uploaded by

zodiakiller01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views104 pages

C

comprehensive notes of C ++ programming language

Uploaded by

zodiakiller01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 104

C ++

CPP- compiler based

javascript- interpreter based

compiler- second, converts high level lang into machine lang, fisrt,checks for errors

** this compilation or language conversion takes place only once. program doesnt get compiled if the
compiler finds an error in between.. compiler creates an exe file after compilation.

a compiler only translates and doent e xecute the program. compiler first compiles the code than make
an exe file which is an idependent file and not dependant on the compiler to run it.

interpreter- interpreter based langs are easy to write, an interpreter exectues a code lline by line. and it
happens everytime you run the code unllike compiler

steps for program development and execution-

1. editing- writing the codeā

neration of that exe file

3.linking library- machine code for commands like cout, cin etc. etc.. the librarries contain the code for
these

4.loading- OS brings the code from hard disk to main memory

5.execution-cpu executes the code


a program which does these all is called an IDE or integrated development environment

(stack- allocation of memory to variables declared in code takes place here

heap- dynamic memory allocation takes place here

code section- this is where the OS brings the code from HDD.)

these 3 are parts of computer memory

cout- console out

cout<<"may i know your name";

getline(cin,str);

this getline is used to extreact and print the whole name, i.e both frst and last name on the screen.
here, str is the variable of type "string"

1byte occupies 8 bits

DATA TYPES AND VARIABLES

1. Primitive- which are already given in the system. types are-

A.int- size of int can be 2 or 4 bytes. it depends on the compiler however modern day compilers use 4
bytes. according to the 2 byte size, range of int is from -32768 to 32767

char- size is 1 byte and range is -128 to 127

boolean (bool)- values are yes or no


float- takes decimal values. size if 4 bytes no need to remember range but u should remember it for char
and int

double- size is 8 bytes. The double is a fundamental data type built into the compiler and used to define
numeric variables holding numbers with decimal points, so basically float and double do same stuff but
remember, DOUBLE has a BIGGER RANGE than float. o when you want a greater range, use double

ASCII(American Standard Code for Information Interchange)

values of some chars and ints as they are stored in comp's memory which you need to learn

a. A to Z- 65 to 90

b. a to z- 97 to 122

c. 0 to 9- 48 to 57

Modifiers- two types:

1. unsigned int- doesn not take the negative values now in int, so all 16 bits are utilized in the positive
side thus taking the range 0 to 65535

2. unsigned char--128 to 127 range becomes 0 to 255

( unsigned modifier is used only with int or char)

3. long int- depending on the initial size assigned to it in compiler(2 or 4), it doubles the initial size. (4 or
8)

4. long double- increaes the size of double data type from 8 to 10 bits

( only these 4 modifiers exist)

** whenever you are declaring a char variable and assigning it a value, use quotes example-

char group='A'.. u dont have to do it in case of other data types


**you can apply numeric values to char data type too**

rules for declaring variable name-

1.first character cant be a numeric value

2. no space in between

OPERATORS

list of operators-

1. Arithematic

2.Relational

3.Logical

4.Bitwise

5.Increment/decrement

6.Assignment

EXPRESSIONS- basically formulas and grouping of these operators

associativity- if the code gets executed from left to right or right to left

precedence- which operator gets the preference

operator precedence

() 1

*(multiply), /, %(mod) 2

+, - 3
( if the precedence collides, code gets executed from left to right)

headrer file u have to include if u wanna use square root function- c math (#include <math.h>)

sqrt- function which performs square root- sqrt (b*b-4*a*c)

poer function (pow), use it like this if u want to find square of v --> pow(v,2)

compund assignment- A compound assignment operator is an operator that performs a calculation and
an assignment at the same time. example- +=, -=,, etc etc.

basically it makes, sum=sum+a equal to sum+=a, second one is faster to do for compiler

INCREMENT OPERATOR-

1. pre inc-> ++x

2.postt inc-> x++

consider int x= 5, y ;

now, y=++ ; (adds one to 5 pehle then stores 6 as y's value so result is, x=6 and y=6)

y=x++ ; ( pehle saves y as 5 then add 1 to x so result is x=6 and y=5)

also z=x++*y (first multiplication ll happen between x and y, then 1 ll be added to x. that ll be new value
of x and z= initial value of x *y)

if z=++x*y ( x ll be increased first then multiplied by y)

DECREMENT OPERATORS - same ismei bhi pre and post, x-- and --x
OVERFLOW

Overflow is a phenomenon where operations on 2 numbers exceeds the maximum (or goes below the
minimum) value the data type can have. Usually it is thought that integral types are very large and
people don't take into account the fact that sum of two numbers can be larger than the range.

Consider a data type var_t of 1 byte (range is 256):

signed var_t a,b;

unsigned var_t c,d;

If c is 200(11001000) and d is 100(01100100), c+d is 300(00000001 00101100), which is more than the
max value 255(11111111). 00000001 00101100 is more than a byte, so the higher byte will be rejected
and c+d will be read as 44. So, 200+100=44! This is absurd! (Note that 44=300-256). This is an example of
an unsigned overflow, where the value couldn't be stored in the available no. of bytes. In such overflows,
the result is moduloed by range (here, 256).

If a is 100(01100100) and b is 50(00110010), a+b is 150(10010110), which is more than the max value
127. Instead, a+b will be read as -106 (note that -106=150-256). This is an example of a signed overflow,
where result is moduloed by range(here, 256).

typecasting

( char x=128;

cout<<(int)x<<endl;

return 0;

[you can do this if you wanna print it in int foorm]

BITWISE OPERATORS
The & (bitwise AND) in C or 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.

The | (bitwise OR) in C or 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.

The ^ (bitwise XOR) in C or 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.

The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second
operand decides the number of places to shift.

The >> (right shift) in C or C++ takes two numbers, right shifts the bits of the first operand, the second
operand decides the number of places to shift.

The ~ (bitwise NOT) in C or C++ takes one number and inverts all bits of it

these operators are used if you have to code for hardware, i.e in electronics, etc.

https://www.javatpoint.com/bitwise-operator-in-c

go to this link to revise them properly

ENUMERATION (enum) [using this increases efficiency of system]

Enumeration is a user defined datatype in C/C++ language. It is used to assign names to the integral
constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an
enumeration.
example-

#include <iostream>

using namespace std;

enum colors{red=5, black};

enum suit{heart, diamond=8, spade=3, club};

int main() {

cout <<"The value of enum color : "<<red<<","<<black;

cout <<"\nThe default value of enum suit : "<<heart<<","<<diamond<<","<<spade<<","<<club;

return 0;

the output ll b the respective nos assigned

TYPEFEFINITION (typedef)[increases readability of program]

example code

#include<iostream>

using namespace std;

typedef int marks;

int main(){

marks m1, m2;

m1=10;

m2=20; }
(yahan pr agr typedef nhi bnaya hota to directly likhna pdta int m1=10, m2=20 aur code lines mei pta hi
ni chlta ki m1 m2 hain kya, so typedef just increased the readability

**both typedef and enum are declared before int main ()

agr enum aur ache se smjhna h to go to

https://www.udemy.com/course/cpp-deep-dive/learn/lecture/10961438#notes

**0 is false and any non zero value is true in cpp.

SHORT CIRCUIT

Short-circuiting is one of the optimization steps of the compiler, in this step unnecessary calculation is
avoided during the evaluation of an expression. Expression is evaluated from left to right. It works under
certain cases when the value of the expression can be calculated certainly by only evaluating parts of the
expression.

DYNAMIC DECLARATION of variables

in this, variables ko initially hi declare nhi kiya jata. zrurt k hisaab se conditional statement k andr declare
kiya jata h. like if() k bracket k andr. example-

int a=10, b=5;

if(true) {

int c=a+b;

cout<<c;

SWITCH CASE
lets learn it directly from an example

int day = 4;

switch (day) {

case 6:

cout << "Today is Saturday";

break;

case 7:

cout << "Today is Sunday";

break;

default:

cout << "Looking forward to the Weekend";

// Outputs "Looking forward to the Weekend"

[ here, day 4 initialize kr diya gya h, aur case 4 neeche h hi ni isliye default option ll be printed.

agr 4 hota, to that day would have got printed aur neeche ka code review b ni kiya jata because of that
break. agr break na hoti, to irrespective of the case, neeche ka case bhi print kr diya jata. thats called a
fall through

only int and char data types (integral data types )can be used in cases.

LOOPS
1.DO WHILE loop executes a staemnet atleast once because usmei process pehle aur condition baad mei
likhi jati h so it first completes that process fir checks kya codition h fir decides ki process firse krni h ya
nahi.

syntax-

do{

process;

while(<condition>);

2.WHILE loop first checks the condition then decides whether to execute or not

syntax-

while(<condition>)

process;

3.FOR loop - also known as counter control loop. this is the commonly used loop. its good to use this
loop when you know exactly how much times u will want to repeat the process.

for(initialization ; condition check ; updation) {

}
PRACTICE LOOPS KAFI ACHE SE THEY ARE IMPORTANT TO MAKE GRIP ON THE LANGUAGE

ARRAYS

initialize an array like this

int A[5]={1,2,3,4,5] where [5] is the size of array and 1,2,3,4,5 are the elements.

suppose if you had written only 1and2 as values then rest of the three values would have been set to 0
by default.

you dont need to set the size of array just keep the brackets empty, size ll be alloted automatically
according to the no. of elements.

using for loop to print elements of an array.

A[8,6,3,9,7,4]

for( int i=0, i<6, i++)

{ cout<<A [i]; }

using FOR EACH LOOP to print array elements

for(int x : A) {

cout<< x; }
here, int is the type of variables, you can set it to "auto" and the computer ll detect the data type on its
own.

in for each loop. if you write cout<<++x ; the output ll be plus one the original value in the array but the
original value in array wont change, only the output ll be affected.

if you want the original value to be changed in the array as well, use refernce. i.e use & before x in the
loop

for(int & x : A)

cout<<++x;

Taking an input as an array.

int A[ ], n=10, i;

cout<<"Enter the numbers";

for( i=0; i<n; i++)

cin>>A[ i ]; }

never use a variable to initialize the size of an array. i.e user se input lekr fir int A[input] krna is a very
ghatiya practice isse acha you do int A[10000] that is still better

LINEAR SEARCH. searching one by one in a sequence.


first off, searching is the process of finding the location of an element.

the element being searched is called the key.

BINARY SEARCH

one condition to use this method is to first have the elements in a sorted order. i.e, ascending
descending etc.

Binary Search is a method to find the required element in a sorted array by repeatedly halving the array
and searching in the half. This method is done by starting with the whole array. Then it is halved.

2D ARRAYS

depicted by- int A[ 3 ] [4 ] where 3 and 4 are the no. of rows and columns respectively.

initializing or declaring a 2D array.

int A[2][3]={ {2,5,9}, {6,9,15}}

here, 2.5.9 and 6.9.15 are the first and second rows respectively or you can also do it as

int A[2][3]= {2,5,9,6,9,15} { first two terms ll go into the row and the rest ll be filled as columns}

Addition in 2 D arrays, or you can say matrices.

( corresponding elements get added or subtracted) like in matrices.


POINTERS

A pointer is a variable used to store the address of specific data.

two types of variables - data variables nd address variables. ( its obvious by the names what they are)

int x=10; (( declaring an dinitializing a data variable)

int *p ; ( declaring a pointer)

p=&x ; ( initializing the pointer)

( lets suppose both these variables take two byte each in the memory and address of data variable =
200/201 and address of address variable= 300/301.

so in the baove example..

cout<<x ll display 10

cout<<&x = 200/201

cout<<p = 200/201

cout<<&p= 300/301

cout<<*p = 10 ( important to remember) ( this is also called dereferencing)

WHY POINTERS

there are three parts of computer memory namely HEAP STACK AND CODE SECTION

the program we write can only access the stack and code section of memory. the program is able to
access the heapp indirectly ny using pointers. even you devices like monitors, keyboards etc. can be
accessed indirectly by the program only. via pointers

HEAP MEMORY ALLOCATION

A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++
programmer. Memory in your C++ program is divided into two parts −

The stack − All variables declared inside the function will take up memory from the stack.

The heap − This is unused memory of the program and can be used to allocate the memory dynamically
when program runs.

Many times, you are not aware in advance how much memory you will need to store particular
information in a defined variable and the size of required memory can be determined at run time.

You can allocate memory at run time within the heap for the variable of a given type using a special
operator in C++ which returns the address of the space allocated. This operator is called new operator.

If you are not in need of dynamically allocated memory anymore, you can use delete operator, which de-
allocates memory that was previously allocated by new operator.

for example

int A [5] ={ 1,2,3,4,5 };

int*p;

( this create an array A and a pointer in the stack )


p=new int [5]; ( creates an array ( with name "p") in heap and the pointer created in stack is holding its
address.. cool isnt it)

unlike stack memory which gets deleted on its own after the function goes out of scope, the memory in
heap foesntt automatically gets deleted. it remains there until the whole program ends. and this isnt
what we want coz we want more free memory to b available.

so we delete it by using "delete". in above case --> delete [ ] p (p is the name of array here and brackets
denote that its an array.

if you do not delete it, its called a memory leak. (no pointer pointing at it and the memory isnt free
either)

after deleting it you can write p=nullptr (says that pointer isnt pointing at anything.

POINTER ARITHMETIC

There are only 5 arithmetic fucntions which you can appply on pointers.

1. p++

shifts the value to next element's address

2. p--

yk

3.p=p+2

shifts the value to 3rd element's( in respect to existing element) address.


4.p=p-2

yk

5. d=p-q

gives the difference, or distance (in terms of elements) bw two elements.

where d is the dis. and p, q are addresses of the two elements.

PROBLEMS WHILE USING POINTERS

1. Unitialized pointer

agr pointer ko koi value nhi di hogi then program ll give an error during run time

2.Memory leak

when you dont dealocate memory from heap and set the pointer pointing to it null. null krne se pehle
delete krna is important.

isliye memory ko delte krna mt bhoolna use k baad

3.Dangling pointer
REFERENCE

consider the following code

int x=10 ;

int &y=x ;

here, &y is the refernce to x. and y is nothing but another name for x.

** a=x (when variable is written at right side, it signifies data value. so a=x means that whatever thats
stored in place of x has to be stored at a's place too, now)

x=25 ( when at left it signifies address value. so x=25 means store 25 at x's address.)

but in case of refernce, i.e int &y=x, x is at right but not data value, here it represents the address. i.e x k
address pr jo h vahi y k pr bhi h ab so basically x and y are same

now y cant be an alias for another variable ever in the program. ab ye sirf x ka hi rahega. like lovers. xD

STRINGS

A string is a collection of characters or letters. ie words or sentences or even paragraphs. size of a string
is dependant on the compiler.

REPRESENTING A STRING

there are two ways


A. USING CHAR ARRAY--> there are several ways in which you can declare and initialize a string using this
method.

1. char x='A' ; (btw this is just a character.i.e a single entity which takes the space of 1 byte. this isnt a
string. for string, u have to make an array)

2. char S[ 10 ] ="Hello" ; (u have to use double quotes for string constants. here. hello is the string
literal/constant. it is to be noted that string ll occupy 6 boxes here i.e 0 1 2 3 4 and 5. the box 5 contains a
string delimeter. the work of this delimeter is to tell us that the string has ended.)

3. char S[ ] = {'H','E','L','L','O'} ;

4.char S[ ]= {65, 66, 67, 68, '\01'} ; ( where 65, 66 etc are ascii codes and \01 represents the delimeter.

( if you make a character array of say, size 20 then it ll hold only 19 elements, rest 1 ll be designated too
derimeter or the /01

5. char *S="Hello" ; ( this array is made by using a pointer and unlike other ways which create a string in
stack, this way is used to create a string in heap.

[ C++ doesnt allow this no. 5 way, instead it uses another class called "string" for this purpose about
which we ll learn later. ]

READING AND PRINTING A STRING

consider the following code

char s[ 20 ] ;
cout<< "enter your name"

cin<< s ;

here if you enter the name as "john" then the output ll be john and 6th place ll be occupied by
derimeter. rest 14 ll be empty

now heres a problem, if instead of john u input john thakur then only "john" ll be read as one string and
thakur ll be read as a separate string but we want john thakur to be one single string here, so for that--->

use

char s[20] ;

cout<<"enter your name" ;

cin.getline(s,20) ;

STRING FUNCTIONS ( to use these, first include the header file #include<cstring>

1. strlen - used to find the length of a string. consider a string s, then to find its length.. write

cout<<strlen(s) ;

2. strcat - concatanates two strings

syntax __ strcat( s1, s2 ) where s1 and s2 are two existing strings to be concatanated and where s1 serves
as the destination string i.e which gets converted to a single large string and s2 serves as the merging
string.
xample-

char s1 [20] = "good" ;

char s2 [20] = "morning" ;

strcat( s1, s2) ;

cout<<s1 ;

here the result ll be goodmorning.

one more version - strncat(destination, source, length) it also contains length option which tells how
many characters from merging string are to be filled in destination.

3. strcpy - strcpy(destination, source ) it copies the source to destination string. one more version
available "strncpy(destination, source, length) which lets u decide how many characters to copy.

4. strstr - strstr( main, sub) this is used to find a substring withing a string.

example lets suppose string s1 contains programming and string s2 contains gram so s2 is the substring
here and strstr function ll help us in finding it.

syntax

char s1[20]="programming" ;

char s2[20]= "gram" ;

cout<<strstr(s1, s2) ;

the result here ll be "gramming" ( it ll also give the characters after our substring)
5. strchr - strchr(main, chr) its just like a strtstr but instead of searching for a str, it searches for a
character, i.e a single alphabet. ( remember, a single alphabet written in double quotes is a string so that
can be used in strstr)

syntax--

char s1[20] = "Programming" ;

cout<< strchr(s1, 'r') ;

this code ll give you rogramming.

theres one more version called strrchr. it searches for the given character from right hand side unlike
normal strchr which does it from the left, so for the code given above if we use strrchr instead, result ll
be ramming.

6. string compare-strcmp(str1, str2)

it compares the first alphabets of two strings according to a dictionary and then give output as negative,
0 or positive accordingly. example, str1= hello and str2=yo. here h comes first so output ll be negative.
the eaxact out put ll be the difference between ascii codes of h and y as y is greater. similarly agr hello ki
jgh zello hota then output would have been positive. ( diff. between ascii codes of z nad y). also, if the
two strings are hello and Hello, then h aur H k ascii codes consider kiye jaenge for the comparision. here,
ascii of h= 105 and that of H=73, so h>H thus output ll be positive.

aur agr dono strings hello and hello hoti then output would have been 0.

syntax-

char s1[20]="minor" ;

char s2[20]= "elder" ;

cout<< strcmp(s1, s2) <<endl ;


the output ll be 8, i.e the diff bw ascii of m and e.

7. string to long- strtol(str1,null, base) this is used to convert a string into long integer.

null- denotes end of the string and has to be mentioned

base- depends on the no. system, if using decimal use 8, binary=2, octa=8 and so on.

8. string to float- strtof(str,null) used to convert a string into float.

syntax for 7. and 8. is as follows

char s1[10]= "235" ;

char s2[10] ="54.78" ;

long int x= strtol(s1, NULL, 10) ;

float y=strtof (s2, NULL ) ;

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

this ll give you the numbers 235 and 54.78 and now u ll be able to use arithmetic operations on them
simply.

9. string tokeniser- strtok(str1, "= ;")

{ here, ; and = are the chosen deriemeters jinke around k token u want, u can change these delimeters
according to your choice.}

it tokenises a key value pair type of string

example you have a string str1 having value x=10 ; y=20 ; z=35= \0
7here, if = and ; are the chosen delimeters, then x, 10, y, 20 z and 35are all tokens, if isntead of ; and = as
delimeters, u take ; as a single delimeter, then the tokens would ve been x=10, y=20 and z=35.
( remember this line is stored in an array format )

char s1[20] = "x=10 ; y=20 ; z=35 ; " ;

char *token=strtok(s1, "=;") ;

while ( token!= NULL)

cout<<token<<endl;

token=strtok(NULL, "=;" ) ;

this ll display x,10,y,20,z,35. if u dont use character string and loop, then it ll print only one token... ( u
need to learn it in deep again)

note- if u use a delimeter which isnt present in the string then no tokenizing ll be done and the whole
string ll be printed in the output.

CLASS STRING

in previous section u learnt to make a string using an array and pointer but in this section we ll use the
built in string class to do so.

to access this class, first include the header file, string. #include<string>
declaration nad initialization--> string str = "hello" ;

this ll create an object str of the type string and store hello in it.

basically it ll create an array jiska size hello se thoda sa bda hoga and then store hello in it (saath mei /01
delimeter bhi)

so, size of the whole array created is called capacity of the string

and actual no. of characters stored in it is called the actual size.

if you increase the actual size of your object, then either jo vacant spaces hongi caacity mei usmei store
hogi stretched string k contents ya to completely naya array bna diya jaega automaticall.

getting input in a string

cin>>str; ( ll only take characters jbtk beech mei space nhi h. i.e for hello world, only hello ll b takem)

getline(cin, str) ; (ll take the whole input)

Basic functions of class string

1. s.length( ) or s.size( ) where s is the string/object name. these functions give you the actual size of
string. (/01 delimeter not counted)

cout<<s.length( );

2. s.capacity( ) tells the capacity of the string

cout<< s.capacity ( ) ;

3. s.resize ( ) lets you resize the capacity


s.resize( 30 ) ;

4. s.max_size( ) gives you the max capacity for that object. depnds on the compiler

cout<<str.max_size ( ) ;

5. s.clear ( ) clears the content of a string

str.clear ( ) ;

6. s.empty ( ) finds out if a string is empty

string str="hello" ;

if ( str.empty ( ) )

cout<< "string empty" ;

else

cout<< "string not empty " ;

in this case, output ll be string not empty.

7. s.append( ) adds new content to the end of existing string s.

example

string s="hello" ;

s.append ("bye") ;
cout<<s ;

the output ll be hello bye.

8. s.insert ( 3, "kk", 1 ) inserts a string at a specific index in the array. here, 3 is the index and kk is the
string and 1 is the no. of characters of the string to be added (no.s counted from left ) if u dont mention
the no. of characters to add, whole string gets added . ( remeber index starts from 0 i.e 0 1 2 3 4 ....)

9. s.replace( 3,5, "aa" ) used to replace specific characters ina existing string.

here, 3 is the index at which replacing ll start, 5 is the no. of characters to be replaced starting from index
3 and aa is the string to be entered as a replacement.

10. s.push_back ('z' ) inserts a single character at the end of a string. here, z ll be inserted.

11. s.pop_back ( ) backspaces last character from the string s.

12. s1.swap( s2 ) swaps two srings s1 and s2.

** single quotes for character and double for string.

13. s.copy ( str, 3 ) copies a string to a character array. where str is the char array and 3 is the no. of
characters you wanna copy.

example, consider a string s="welcome" ; and a character string i.e char str [10 ] ;

so, s.copy (str, 3) ll give the result "wel" and in place of come, it ll give some garbage value. this means
that /0 i.e null character is not included with the 3 characters when we copy. so to keep out that garbage
value we ll have to manually assign the null character. and we do it by typing str[ 3] ='\0' ; after copying
the string. now we ll only have "wel" as the result.
14. s.find (str) or (char) this finds the specific string or character inside a bigger string and gives the
index of it. here, s is the parent string jismei dhoondna h bcche string ko. example

consider a string str="how are you"

so, str.find ("are") ll give index 4.

similarly, u can also search for a character as follows.

str.find( 'y') [ single quotes for a character] ll give you index no. 8

15. s.rfind (str) where str is the string to be found and s is the parent string. this is similar to s.find but
instead of searching the string from left, it doest it from the right. remember ( counting hmesha left se hi
hogi, bs search right se krega ismei)

remember ** suppose u search for a string or char which doesnt exist in the parent string, then the
result will be an index out of the range of that string.

e.g range of "how are you" is 10, and if u search for k inside it, it ll return any value outside of 0 to 10.
(exact value depends from compiler to compiler) that way u can find out if the str or char is presnt inside
parent or not.

16. s.find_first_off( ) consider a string str= "hello world" its indices are from 0 to 10. now if you type

str.find_first_off ( 'l') then result ll be 2. i.e it finds first occurence of the specified character.

if u also specify a number alongside that specific character, then it ll start searching the character from
that specified index. e.g

str.find_first_off ( 'l', 4) now the result ll be 9.

** suppose u type a string as folloes str.find_first_off("le") then in this case it will give u index of
whatever that comes first among l and e. so the result ll be 1. ( as e stands at index 1) i.e it doesnt take a
string, it ll just separate out the characters and then search for them instead for a string

17. s.find_last_off ( ) its similar to the no. 17 function, it just searches for the character from right end.

18. s.substr ( start, number) it extracts a substring out of a parent string. where start is the index jahan
se extraction start hogi and number is the no. of indices from "start" jahan tk extraction hogi. e.g
consider a string str="programming"

now, str.substr (3, 4); ll give you a substring gram.

18. s.compare( str ) ; where s and str are two strings to be compared on the basis of their occurence in
dictionary. if by chance, they only differ in case, i.i lower case upper case then their ascii codes are taken
into consideration.

remember, string s ll be compared against string str.

(if first string has smaller ascii code or comes pehle in dictionary, then reult ll be negative, if ulta, then
reult is positive, or if both strings are same then the result is 0 )

e.g

string str1="Hello" ;

string str2="hello" ;

cout<<str1.compare(str2) ;

here, the result ll be negative 32 which is the diff between ascii code of H and h.

STRING OPERATORS

1. at( ) --> this is same as the subscript operator [ ]

consider a string str= "holiday" ;

cout<< str.at (4) ; gives d.

if u use cout<< str [4] ; then the result ll be same.


but u have to remember that [ ] can do both, read and write while s=at ( ) can only write.

e.g, you can change holiday to holimay by command str[ 4 ]= 'm' ; but not by using at( ) operator.

2. + ( concatenate) and = ( assignment) operators

string str1= "hello" ;

string str2="world"

str1=str1+"world, how are you? " ; ( concatenation)

cout<< str1 ;

result ll be "hello world, how are you? "

if instead of concatenation, u type str1=str2; ( this line ll copy contents of str2 to the str 1)88888888888

and cout<<str1 ;

then result ll be "world".

ITERATORS

these are used for travelling or accessing all the characters of a string.
suppose theres a string str = "today" ;

Declaring an iterator

string: : iterator it ;

Assigning an iterator

it=str.begin ( ) ( here begin () is the starting index i.e "t" of today )

similarly theres an end ( ) which is the ending index.

now, if you want to iterate a string, then u have to run a for loop. for example, here as str= today

for( it=str.begin( ) ;

it ! = str.end ( ) ; i++ ) where it!=str.end( ) says to keep iterating until u hit the ending index.

now, to print the string u can give a command cout<<*it ;

it ll print "today".

( u must unerstand that iterator kinda plays like a pointer here sou gotta dereference it by using * while
giving cout.

accessing and iterating from reverse direction

here, instead of string: : iterator it ; you do string: : reverse_iterator it ;

and in the loop, u use for( it=str.rbegin ( ) ; it ! = str.rend ( ) ; it++ )

FUNCTIONS
is a piece of program code which performs a specific task. these are useful in modular programming. a
collection of functions is called a library. exmple cpp has a lot of built in functions in its library.

every cpp program must have a main function.

void main ( ) { proram } [ this is the entry point of our program aur starting from here everything is
executed. ]

when u write everyhting inside a main function then the code has asingle function and its called
monolithic programming.

problems with this type of programming.

1. if theres an error in single line, then theres an error in the whole program.

2. u can write lengthy codes only if u remember the old parameters and values in the program..

3. it can be written by only one person, so teamwork isnt feasible.

4. a program written in single function may become so big that it refuses to fit in some computer's
memory.

so instead of this, we distribute a program into pieces, i.e separate functions. and this is called modular
programming.

syntax-->

returntype function name (parameter list )

where parameter list basically is input (function can take 0 or more inputs)

and returntype is the output (it might return a value or it might not, but at most, it returns one value
only)

if function isnt returning any values then the return type should be "void".
rules for naming of a function are same as that of naming a variable.

avoid user interaction i.e cin and cout inside functions except main function

heres an example of a function adding two numbers

int add( int x, int y )

int z ;

z=x+y ;

return z ; } ( this function ll add x and y and store the sum in z. )

void main ( )

int a=10,b=15,c ;

c=add (a, b) ;

cout<<"sum is"<<c ;

( MEMORY MEI KYA LENA DENA HOTA H ISKA TO SEE THAT SEE LECTURE NO. 132) SIR SAID ITS
IMPORTANT.

FUNCTION OVERLOADING

Function overloading is a feature of object oriented programming where two or more functions can have
the same name but different parameters.
In Function Overloading “Function” name should be the same and the arguments ( also called the
parameters) should be different.

Function overloading can be considered as an example of polymorphism feature in C++.

example

int add( int x, int y)

return x+y ; }

this was function 1.

int add ( intx, int y, int z )

return x+y+z ;

and this was function 2

void main( )

int a=10, b=5,c, d ;

c=add(a,b) ; (ll call funtion 1)

d=add(a,b,c); (ll call function 2)

yahan ye dono functions are basically same. ..( same names just differet argument list) this is called
function overloading.
now here, remember.

int add( int x, int y) ;

and float add01( int x, int y ) ;

these are different. this isnt the case of function overloading but the case of naming difference. agr dono
ka naam "add" hota with even different return types tb bhi overloading hi hota,

overloading k liye function name same hona chahiye bs parameter list alag hogi.

FUNCTION TEMPLATE

The simple idea is to pass data type as a parameter so that we don’t need to write the same code for
different data types.

example__ below is a template function for finding out the maximum integer in one function and max
float in another one.

template <class T>

T max( T x, T y )

if(x>y)

return x ;

else return y;

main ( )

int c= max(10,5) ;

float d=max( 10.5f,6.9f) ;


( argument mei data type same honi chahiye ffor this to work coz u are only using one template T. )

DEFAULT ARGUMENTS

Following is a simple C++ example to demonstrate the use of default arguments. Here, we don’t have to
write 3 sum functions, only one function works by using default values for 3rd and 4th arguments.

int sum(int x, int y, int z = 0, int w = 0)

return (x + y + z + w);

// Driver Code

int main()

// Statement 1

cout << sum(10, 15) << endl;

// Statement 2

cout << sum(10, 15, 25) << endl;

// Statement 3

cout << sum(10, 15, 25, 30) << endl;

return 0;
( basically function override krne ki zrurt nhi pdegi just because of different no. of arguments in
upcoming functions. all u have to do is initialize more arguments in parent function jaese x=0 y=0 aur
compiler unhe tbhi use krega agr neeche vale function mei tum kuch value daloge un extra arguments ki.
otherwise it ll remain 0 aur compiler sirf utne hi argument nikallega uupr se jinmei by default value 0 nhi
hogi aur jinki zrurt hogi.

CALL BY VALUE

The call by value method of passing arguments to a function copies the actual value of an argument into
the formal parameter of the function. In this case, changes made to the parameter inside the function
have no effect on the argument.

( function definition to swap the values of two integers x and y)

void swap(int x, int y) {

int temp;

temp = x; /* save the value of x */

x = y; /* put y into x */

y = temp; /* put x into y */

return;

}
Now, let us call the function swap() by passing actual values as in the following example −

#include <iostream>

using namespace std;

// function declaration

void swap(int x, int y);

int main () {

// local variable declaration:

int a = 100;

int b = 200;

cout << "Before swap, value of a :" << a << endl;

cout << "Before swap, value of b :" << b << endl;

// calling a function to swap the values.

swap(a, b);

cout << "After swap, value of a :" << a << endl;

cout << "After swap, value of b :" << b << endl;

return 0;

}
When the above code is put together in a file, compiled and executed, it produces a result

Which shows that there is no change in the values though they had been changed inside the function.

oopr vale example mei a=100 and b=200 are the actual arguments and they get copied to the formal
parameters i.e x and y of the swap function which has been written at the top. to sb changes usi oopr
vale swap function mei hote hain and when its done tb memory se sara data clear hojata h without there
being any change in actual parameters.

CALL BY ADDRESS

The call by pointer method of passing arguments to a function copies the address of an argument into
the formal parameter. Inside the function, the address is used to access the actual argument used in the
call. This means that changes made to the parameter affect the passed argument.

To pass the value by pointer, argument pointers are passed to the functions just like any other value. So
accordingly you need to declare the function parameters as pointer types as in the following function
swap(), which exchanges the values of the two integer variables pointed to by its arguments.

// function definition to swap the values.

void swap(int *x, int *y) {

int temp;

temp = *x; /* save the value at address x */

*x = *y; /* put y into x */

*y = temp; /* put x into y */

return;

}
// function declaration

void swap(int *x, int *y);

int main () {

// local variable declaration:

int a = 100;

int b = 200;

swap(&a, &b);

u ll find ki iska result ye hoga ki unlike pass by value, ismei actual arguments swap hojaenge.

remember***

if a=10;

and int* b=&a

then b is the pointer variable to a.

cout<<b and cout<<&a give the address of a.

cout<<*b gives the value of a i.e 10.

CALL BY REFERENCE
( a refernce to a variable is just a nickname to that variable)

The call by reference method of passing arguments to a function copies the reference of an argument
into the formal parameter. Inside the function, the reference is used to access the actual argument used
in the call. This means that changes made to the parameter affect the passed argument.

( remember one very imp thing**

as you know ki memory mei 3 section hote hain. code section, where code is saved stack jahan variables
store hote aur heap jahan se extra memory access kr skte..

now typically jb tum 2 alag function likhte ho tb code section area mei 2 diff jagah assign hoti h un dono
functions ko pr when u use call by reference tb the function other than main function is copied in the
main function only so only one place is there for both functions basically ek hi function hota vo. these
type of functions are also called as inline functions.

To pass the value by reference, argument reference is passed to the functions just like any other value.
So accordingly you need to declare the function parameters as reference types as in the following
function swap(), which exchanges the values of the two integer variables pointed to by its arguments.

// function definition to swap the values.

void swap(int &x, int &y) {

int temp;

temp = x; /* save the value at address x */

x = y; /* put y into x */

y = temp; /* put x into y */

return;

}
let us call the function swap() by passing values by reference as in the following example −

// function declaration

void swap(int &x, int &y);

int main () {

// local variable declaration:

int a = 100;

int b = 200;

cout << "Before swap, value of a :" << a << endl;

cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/

swap(a, b);

RETURN BY ADDRESS

functions can return the addresses too.

( few videos have been skipped. i am going to jump to OOPS now)


VARIABLES

Global variables- can be accessed and used anywhere in the code

local variables- are written in a specific function and can be accessed inside that particular function only.
once that function finishes that variable is terminated too in order to free the memory.

SCOPING RULE

take the following code

int x=10; ( global variable)

int main( )

int x=20; ( local variable )

int x=30; ( variable insie sub block )

cout<<x ; this ll print 30

cout<<x ; this ll print 20

cout<<: : x ; this ll print 10. (10 print na hota if scope resolution operator wasnt used. scope
res operator [ : : ] is used to print a global variable with same name as that of a local variable inside that
function.)

STATIC VARIABLE

what is a global variable?

jo program k end tk memory mei rahe aur sbhi use access kr paayein.

static variable is a global variable but only the function its written in can access it. i.e, memory mei
rahega end tk bus accessing pr restriction h.

declaring a static variable.

static int v=0 ; ( just use the static keyword)


RECURSIVE FUNCTION

A function that calls itself directly or indirectly

for example,

void fun( int n)

if ( n>0)

cout<<n<<endl ;

fun ( n-1 ) ;

output of this code ll be 5 4 3 2 1

here, the function fun is callling itslef again and again just the value inside is modified.

POINTER TO A FUNCTION

Consider the following example

void display ( )

cout<<"hello" ;
}

int main ( )

void ( *fp ) (function parameters ) ; [ This is the declaration of a pointer ]

fp=display ; [initialization. this ll store address of display function in the pointer]

( *fp ) ( function parameters) [ This is calling of the function ]

OBJECTED ORIENTED PROGRAMMING

consider, OOP a govt. now a govt has various sectors and departments like water, transport, education
etc. these all cann be considered as objects in OOP. these objects can further contain functions and data
related to those functions.

jo pehle hum krte the thats called modular programming which is nothing but just a collection of
functions.

OOP is better cuz its much sorted and allows multiple people to work on developing a software at a time.

PRINCIPLES of object orientation

1.Abstraction

Abstraction is the concept of object-oriented programming that “shows” only essential attributes and
“hides” unnecessary information. The main purpose of abstraction is hiding the unnecessary details from
the users.

example u have used cout function a thousand times but u dont know how it works. thats an abstract for
you.

2.Encapsulation or data hiding

encapsulating the data and functions into a single unit, in this case a class storing data and functions to
make it safe from mishandling. (remember, not to protect the privacy( kisse protect krra tune hi to likha
code), but to protect it from mishandling) example how a set top box is a single unit and uske andr saari
wires and ICs.

( private aur public yahan use hote)

we hide the data (pvt) and show the functions(public)

3. Inheritance

example, theres a class CAR and then there are other classes called BMW, suzuki, toyota. now all these
latter classes inherit a bsic thing from the class CAR, engines and 4 wheels etc. but they also have their
own modified feature. so this is inheritance.

4.Polymorphism

u ve to learn to drive a car. what ll you learn? suzuki toyo or bmw?

you ll learn the class CAR. aur usse you ll learn toyo bm and suzu. kuch diff honge driving style mei but u
ll ve learnt how to drive a car. this is polymorphism

CLASS VS OBJECT

PRashant is an object and HUman is a class. ( his class)

We can say that a class is the blueprint of an object.

We can also say that an object is an instance of a class

WRITING A CLASS AND OBJECT

Consider the following code

class rectangle ( declaring a class)

[
public : ( access specifier. by default class k andr ka maal is not accessible)

int breadth ; ( declaring variables )

int length ;

int area ( ) ( making function area to find the area of rectangle )

return length*breadth ;

int perimeter ( ) ( making functions )

return 2*(length + breadth ) ;

} ; <--- this semicolon is important

( class rectangle finishes here)

void main ( )

rectangle r1, r2 ; (making objects r1 and r2)

r1.length=10 ; ( accessing the class variables through . (dot) operator )

r1. breadth=5 ;

cout<< r1.area ( ) ; (accessing member functions thu dot operator)

r2.length=3 ;
r2.breadth=5 ;

cout<<r2.area ( ) ;

It should be noted that data members r1 and r2 will occupy memory and not the functions area and
rectangle.

here, r1 and r2 are user defined data members.

DOT operator is used to access both data members and member functions

POINTER TO AN OBJECT

in the baove code, in main function you accessed the data members using their name and dot operator.
but you can access those data members using a pointer too

consider the same above code

in main function,

int main ( )

rectangle r ; ( creating an object)

rectangle *p ( creating a pointer )

p=&r ; ( storing object r's address in pointer p )

p-> length=10 ; ( using a pointer to access data member length) here, -> is the dereferncing operator.

p->length=10 ; is doing the same job as that of r1.length=10 ;


using this you can also access member functions.

ye jo oopr sb bnaya hmnei its taking place inside stack

CREATING AN OBJECT INSIDE HEAP

its done using pointer

consider the following code

void main ( )

rectangle *p

p=new rectangle ; ( creates an object in the heap)

you can also write

rectangle *p = new rectangle ;

DATA HIDING

Data members should always be private and member functions should be public

data members should be private so as to ensure that no mishandling of data is there.

members functions are features and operations that you give to the user so vo to public hi rahenge.

example, in a TV set top box, member functions are the buttons and data members are the wires inside.

ab dikkt ye h ki when writing a class, tu data members ko pvt krdega aur member functions ko public. pr
jb function ko likhega aur us function ko vo data access krna hoga, tb vo nhi kr paega access ( cant read
or write private things)

to use access krvane k liye you ll have to write separate functions.

consider the following code

class rectangle

private :

int length ;

int breadth ;

public :

void setlength ( int l ) ( will save value of length in variable length )

length=l ;

void setbreadth ( int b ) ( saves breadth )

breadth=b ;

int getlength ( ) ( will read value of length )

return length ;

}
{

int getbreadth ( ) ( will return value of breadth)

return breadth ;

};

now, to call these functions while writing the main function

instead of writing r.length, you ll write r.setlength

in the above example,

set will change the value of data member.

this function is called a mutator

get will give you the value of data member

This function is called an accessor

together,.these both are called property functions coz

data members are a prooperty. )

CONSTRUCTORS IN CPP
A constructor is a special member function with same name as that of the class

its used to initialize the objects of its class

it is automatically invoked whenever an object is created.

When you create an object rectangle r, it is created but we do not write the function to create this
object. there is an inbuilt fucntion which creates this object and its called default constructor.

you can create your own constructor too i.e a user defined constructor.

if you donot write a user defined constructor then the program creates a default constructor or a built in
constructor

constructors do not have a return type

a constructor might take arguments or it might not

There can be many constructors in a class. It can be overloaded but it can not be inherited or virtual

1. Non parameterized constructor ( no arguments) ( you want a car)

class rectange

private :

int length ;

int breadth ;

public :

rectangle ( ) ( a constructor not taking any arguments)

length=0 ;

breadth=0 ;

}
2. Paramaterized constructor ( takes arguments ) ( you want a volvo xc90 )

class rectange

private :

int length ;

int breadth ;

public :

rectangle ( int l, int b ) ( a constructor taking arguments )

setlength ( l ) ; ( this will ensure ki negative value na le length breadth ki)

set breadth ( b ) ;

3. Copy constructor (A copy constructor is a member function that initializes an object using another
object of the same class) ( you want the same car which kartik aryan has )

class rectange

private :

int length ;

int breadth ;

public :
rectangle ( rectangle &rect ) [ we take r by reference and not by value taki memory mei new r na bann
jaye ]

length=rect.length ; ( Lhs is for the new construstor and rhs us constructor k liye which is being
copied )

breadth=rect.breadth ;

};

int main ( )

rectangle r2 ( r ) ; ( passing r as a parameter to object r2 )

yahan p

agr firse zrurt pde constructors pdhne ki then watch this video

https://www.youtube.com/watch?v=hAA8FBq2bA4

DEEP COPY CONTRUCTOR

but first whats the problem with copy constructor?

In shallow copy, an object is created by simply copying the data of all variables of the original object. This
works well if none of the variables of the object are defined in the heap section of memory. If some
variables are dynamically allocated memory from heap section, then copied object variable will also
reference then same memory location.
This will create ambiguity and run-time errors dangling pointer. Since both objects will reference to the
same memory location, then change made by one will reflect those change in another object as well.
Since we wanted to create a replica of the object, this purpose will not be filled by Shallow copy.

Deep copy allocates separate memory for copied information. So the source and copy are different. Any
changes made in one memory location will not affect copy in the other location. When we allocate
dynamic memory using pointers we need user defined copy constructor.

suppose you are copying an array to baki to copy constructor jaesa hi syntax hoga bs vo jo pointer diya
jaega vo ek new array ko diya jaega. that array ll be an exact replica of the array to be occupied and you
can simply do it by p=new int [ A ]

TYPES OF FUNCTIONS IN A CLASS

accessors

mutators

argumented constctors

non argumented constructors

copy constructors

facilitators ( functions like calculating area and primeter... i.r which actually do something )

inspectors or enquiry functions ( example will chck if some figure is a square)

inspctors return integer values or boolean expressions true or false

destructors

If you write all these functions in a class then that class is known as a perfect class
SCOPE RESOLUTION OPERATOR ( : : )

Uses of the scope resolution Operator -->

1.It is used to access the hidden variables or member functions of a program.

2.It defines the member function outside of the class using the scope resolution.

3.It is used to access the static variable and static function of a class.

4.The scope resolution operator is used to override function in the Inheritance.

But here we will discuss only about point 2.

see, we can write functions related to a class inside that class itself or we can write them individually
outside that class. but writing them outside the class is preferred.

to jb class k andr likhna hota h tb to we can write them simply without adding any other keywords and
stuff but agr class k bahar likhna ho to scope resoultion daalna pdta h tbhi lgta h compiler ko pta ki ye
function us specific class pr apply ho raha h

syntax :

suppose theres a class named rectangle aur uske andr ek function hona chahiye jismei area will be
found.

so using scope resoultion operator,

int Rectangle : : Area ( ) ( oprator se pehle you have to write class name)

return length * breadth

};

never write complex functions inside a class.

a function wrtten inside a class is called an inline function

if you wanna make a non inline function inline, simply write "inline" before calling that function in the
class. { likha vo class se bahar hi jaega bs class mei call krte time function se pehle inline likha h }
THIS POINTER ( this-> )

This is a pointer which is a pointer which points to the object which is being created/invokes the
member function.

ye us object ko point krta h jisne member function ko call kiya

class A {

int a ;

public :

void setdata ( int a) ( setdata data set krta h vo function h)

{ this->a = a ;

in the above example, we are setting the value of a

lekin pehle to hum aesa krte the

void setdata ( int a1 )

a = a1 ;

so this pointer is just helping us by saving us from the ambiguity of variable names.

ye practice k saath hi aega aese padhkr shayad pta na chle

STRUCT VS CLASS

A struct is nothing but a class. the only difference is that class mei everything is private by default and in
struct everything is public by default

OPERATOR OVERLOADING

Thoda confusing h smjh hi ni aaya notes mei likkhun kya. practice krke dekh smjh aaya to vrna you tube.

OPERATOR OVERLOADING BY USING FRIEND FUNCTION

If a function is defined as a friend function in C++, then the protected and private data of a class can be
accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a class
starting with the keyword friend.

so that friend function's maii body can be written outside the class without using the scope resolution
operator

consider the following code

main ( )

complex c1 (3, 7)

complex c2 ( 5, 4 )

complex c3 ;

class complex {

private :

int real ;

int img ;
public :

friend complex operator + ( complex c1, complex c2 )

};

complex operator + ( complex c1, complex c2 )

{complex t ;

t. real=c1.real +c2.real ;

t.img=c1.img +c2.img ;

return t ;

when calling the friend function, use the keyword "friend" before that function when calling it inside the
class.

OVERLOADING INSERTION (CIN) AND EXTRACTION OPERATOR (COUT)

you must know that cin is a predifened object of istream class and cout is a predfined object of ostream
class.

combination of these two classes is called iostream

consider this

int a=10;

cout<<a ;

here << ki left side mei ek predifend object right side mei predefined variable h. remember that << sign
always follows this trend

now lets use this operator on user defined objects


right side mei jo variable h vo bhi basically ek object hi h, so we are basically using two classes. isliye
overloading k time bhi 2 classes ka use hoga

when using two classes we have to go for friend

#include<iostream>

#include<cstudio>

class stu {

int id;

char name [10] ;

public :

friend void operator >> ( istream &in, stu &s)

[ here, >> is the extraction operator used with cin. istream is the class which the 'in' is an object of and
&in is the reference object. basically &in is nothing vut a reference name to 'cin'.

stu is the user defined class and &s is also a reference variable/object of the class stu. ]

in general, a friend function is defined outside the class but while doing operator overloading, it can be
defined in the class itself.

( outside too)

cout<<"enter stu id and name" ;

in>> s.id>>s.name ; ( instead of cin you can use directly in now)

}
friend void operator << (ostream &out, stu &s )

out<<"ID=" << s.id << endl ;

out<<"name="<< s.name ;

void main ( )

stu s ;

cin>> s ; ( able to apply cin and cout on user defined object s)

cout<< s;

INHERITANCE

acquiring the features of an existing design into a new design

consider the following code

class rectangle

{
privatte :

int llength ;

int breadth;

public :

rectangle ( int l=0, int b =0 ) ;

int getlength ( ) ;

int getbreadth ( ) ;

void setlength ( int l) ;

void setbreadth ( int b) ;

int area ( ) ;

int perimeter ( ) ;

class cuboid : public rectangle (new class cuboid , inheriting publicly from class rectangle )

private :

int height ; ( us, only giving height bcoz length and breadth of cuboid ll be inherited from class
rectangle )

public :

cuboid ( int l=0, int b=0, int h=0 ) ( a constructor setting dimensions of cuboid)

height =h ;

setlength ( l ) ; ( constructor cant directly access l and b coz vo private data members hain vo class
rectangle so instead we will use set methods to access length and breadth)

setbreadth ( b ) ;
}

int getheight ( ) ;

void setheight ( int h ) ;

int volume ( )

return getlength ( )*getbreadth( )*height ;

};

int main ( ) {

cuboid c ( 10,5,3) ;

cout<<c.volume( ) ;

iska output ll be 10*5*3=150

CONSTRUCTORS IN INHERITANCE

when both base and derived class have constructors, the constructor of base class is executed first

in multiple inheritance, base classes are constructed in order in which they appear in class declaration

in multilevel inheritance, the constructors are executed in the order of inheritance


SPECIAL SYNTAX

cpp supports a special syntax for passing arguments to multiple base classes.

in it, the constructor of derived class recieves all the arguments at once and then passes the calls to the
respective base classes.

syntax--> dervedconstructor (arg1,arg2,arg3) : baseconstructor1 (arg1,arg2), baseconstructor2


(arg3,arg4) {

..... }

Special case of virtual base class

the constructors for virtual base classes are invoked before a non virtual base class

if there are multiple virtual classes, then they are ivoked in the order declared.

example consider this

class A : public B, virtual public C

here, the order of execution will be C( ) then b( ) and then a( )

isA vs hasA

A class can be used in two ways. either it can be used for derivation of another class or its object can be
used in another class

consider three classes.

rectangle- base class

cuboid- has been derived from rectangle


table- uses an object of rectangle

here, cuboid is basically a rectangle. they both share isA relation and table has an object of rectangle so
they both share a hasA relation

ACCESS SPECIFIERS

Private

protected

public

1.in a derived class, you can access only public and protected members.

2.while coding in the same class, yu can access all three, public private and protected

3. over an object, you can access only public members

TYPES OF INHERITANCE

Single

multiple ( derived class has multiple base classes)

multilevel

hierarchical ( multiple derived classes have a single base class)

WAYS OF INHERITANCE

there are three ways in which derived classes can be derived

publicly

prviately ( by default)
protectedly

consider following three classes

1.class parent ;

2.class child : protected parent ;

3.class grandchild : public child

here, child will be able to access both public and protected members of parent but they will become
protected once inherited by the class child.

so neeche grandchild ll be able to inherit them in protected format only

1.class parent ;

2.class child : public parent ;

3.class grandchild : public child

child ll ve access to both piblic and protected and they ll be saved in that format only

grandchild ll access both public and protected of child

1.class parent ;

2.class child : private parent ;

3.class grandchild : public child

both public and protected of class parent will become private after coming to child and grandchild wont
be able to access anything

**jb hum privately dete hain aage kisi ko kuch to basically what we are saying is that ki bhai tu le le
sbkuch pr is specific chiz se chhed chhad mt krio**

GENERALIZATION vs SPECIALIZATION

1. Generalization- its a bottom up approach. i.e, we assign a base class from derived classes. in actuality,
no functional base class exists. the base class has nothing to give to derived classes opposite to whats
supposed to happen, for example

circle rectangle quadrilateral etc are classes and they are all shapes.

so a circle, quadri etc. exist on their own but a shape on its own is nothing.

the purpose of generalization is to achieve polymorphism. same name different functions

2. SPECIALIZATION- its a top down approach. e.g fortuner was manufactured after innova and is based
on innova. so both innova and fortuner exist in reality and fortuner gets some of its features from
innova. this is an example of specialization.

BASE CLASS POINTER DERIVED CLASS OBJECT

a pointer of base class can point to an object of derived class

but using that pointer you cant call or execute functions of that derived class

functions hmesha base class k hi execute honge if you call them using base class pointer
consider the following code

class base {

public:

void fun1 ( )

cout<<"fun1 of base"<<endl ;

};

class derived : public base

public :

void fun2 ( )

cout<<"fun2 of derived"<<endl ;

};

int main ( )

derived d ; ( object d of derived class )

base *ptr =&d ( assigning address of d to pointer ptr of class base )

ptr-> func1 ( ) ; using ptr to call a function

ptr->func2 ( ) ; [ same as above but this ll throw error because fun2 is of derived class and pointer wont
execute ]
return 0 ;

(**you cant assign a derived class pointer to a base class object but you can assign base class pointer to
derived class object. this is because base class is not a derived class but the derived class is essentially
that base class ( coz it has been derived from that base class) )

FUNCTION OVERRIDING

allows us to use a function in the child class that is already present in its parent class. you can re define
that function in the child class.

consider this

class parent {

void display 9 )

{ cout<<"display of parent" ;

};

class child : public parent

void display ( )

{ cout<<"display of child" ;

};

int main ( )

parent p ;
p.display ( ) ;

child c ;

c.display ( ) ;

return 0 ;

in this case agr child class mei koi bhi function nhi hota then, the output would have been "display of
parent " in both cases

but since we overloaded that fucntion in child class, so now the output ll be "display of parent" and
"display of child "

** if you use the base class pointer method to call the function, still the function present in base class
will be called and executed and not the overrided function

** if you wanna call the overrided function using the pointer, then you will have to make the original
function, a virtual function. that can be done by simple writing "virtual" before you mak ethe function
example --> virtual void fun( ) (.... }

POLYMORPHISM

basically you will give the exact same commad but different functions will be called.

[ Pure virtual function--> when you assign a virtual function=0

purpose-- to force the child classes to override the parent classes's virtual function.. i.e to achieve
polymorphism]

btw the purpose of inheritance is reusibility and polymorphism


reusibility s simply being able to use the earlier written code example the derived class can use the pr
written functions in its base class

whereas once you override or redefine the functions, it becomes polymorphism.

ABSTRACT CLASSES

a class having a pure virtual function.

** you cant create an object of that class but you can create a pointer.

virtual function mtlb uska koi real use nhi h, its just a prototype for the derived classes. its just there so
that hum uska ek pointer bnakr baki derived classes k function execute krva paein i.e polymorphism krva
paein

example--

class base {

public : virtual void fun( ) = 0 ;

};

class derived : ublic base

public :

void fun( )

{ cout<<"derived fun" ;

}};

base *p=new derived ( ) ; [ base class pointer to derived's object ]

p->fun( ) ; [ prints "derived fun" ]


here, fuction fun is a purely virtual function and thus has no body in the base class. its just a hollow
function. so the class base has no use except that we will make a base pointer of it which ll help in
attaining polymorphism.

class type purpose

all functions are concrete reusiibility

some concrete some pure virtual (abstract) reusibility + polymorphism

all functions purely virtual ( abstract class) polymorphism

FRIEND FUNCTION

Friend Class A friend class can access private and protected members of other class in which it is
declared as friend. It is sometimes useful to allow a particular class to access private members of other
class.

but remember, when declaring a class as a friend, us class ko declare krna pdega pehle, just declaration
hi, uske andr ka saaman chahe baad mei likhna.

Friend Functions work just like a 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

class test

private : int a ;

protected : int b ;

pulic : int c ;

friend void fun ( ) ;


};

void fun ( )

test t ;

t.a=10 ;

t.b=15 ;

t.c=9 ;

yahan agr friend nhi declare kiya hota, then function void which has been called upon object t and which
is using variables a b and c woud not ve been able to access b and c

remember, you still cant directly access the variable a

suppose you write a=2 ; while writing the function body.. that wont be possible bcoz a cant be accesses
aese. it can only be accessed while using for an object.

STATIC MEMBERS IN CPP

Static data members are class members that are declared using static keywords. A static member has
certain special characteristics. These are: Only one copy of that member is created for the entire class
and is shared by all the objects of that class, no matter how many objects are created

consider this

class test {

private :

int a;

int b;
public :

static int cout ; ( declaration of static variable count of type int)

test ( ) ( constructor )

a=10 ;

b=10

cout ++ ;

};

main ( ) ;

test t1 ; ( making objects t1 and t2 )

test t2 ;

in this code, when we create t1 and t2 then in dono objects k liye alag se a nd b will be assigned. t1 k liye
separate a and b while t2 k liye separate a and b. ( dono ki value ll be 10 in both cases kyunki intialize hi
vo ki h)

but since count is static, isliye vo ek hi bnega memory mei and both t1 and t2 ll share it.

so just suppose that t1 was called and cout was initially at 0, to uske baad count++ =1

and uske baad t2 ll be called and uski execution baad count++ = 2.

** when you declare a static member inside a class, that member has to be declared again outside the
class using scope resolution
i.e, in above case one more line of coded ll be added outside class test

int test : : count=0

** static members can be accessed using objects or they can also be accessed directly using class name.

STATIC MEMBER FUNCTION

basically ye bhi vahi h, ek static member.

but the thing to be remembered is that these functions can only access static data members and not non
static members.

thus, static member functions also belong to a class.

isliye they can be called on an object aur directly bhi.

example [ continuation of above code ]

static int getcount ( )

return count ;

here, cout<<test : : getcount ( ) ; is also valid as well as cout<<t1.getcount ( ) ;

INNER/NESTED CLASSES

a nested class is a class jiske andr ek aur class likhi jaye which is useeful for that main class

basically us poori outer class ki complexity kamm krta h sorted lgta h sb

class outer {

public :
int a ;

static int b ;

void fun ( )

{ i.show ( ) ; [accessing a function of inner class via object]

cout<<i.x ; [ accessing x of inner class via object]

class inner {

public :

int x=25 ;

void show ( ) {

cout<<b ;

};

inner i ; ( outer class making an object of inner class ye object tbhi bnega once the inner class has been
declared usse pehle nhi bn skta )

int outer : : b=20

** inner class can dierctly acces the members of outer class if they are static.

outer class can make an object of inner class. using that object it can access all the members of inner
class. ( public member directly ho skta h access but noyt private and protected members)

to make the objects of inner class outside the outer class,

outer : : inner i ;
EXCEPTION HANDLING ; a feature of OOP

There are three types of errors in CPP

1. Syntax error- mistake while writing the code.

compiler identifies this error

2. Logical error-You wanted to perform an action so wrote a code for it but when you compiled it the
results were different. so theres something wrong in your logic.

Debugger helps in resolving this error. it runs the code line by line.

3.Runtime error- ek bar client ko software de diya aur vo use dhng se na chlaye then run time error migh
happen.

Some reasons for run time error are -

a. Bad input. for an instance program ne kaha integer value input kro aur user ne string daal di.

b. program ko internet connection chahiye but your comp isnt connected to interernet.

c. the program needs to access some files on your computer but you have deleted them.

so basically its the unavailablity of resources. ( external to the program )

now these run time errors are called exceptions.

so an exception is basically a situation where we get run time error.

so exception handling --> telling the user exactly what is the problem and then giving him guidelines to
resolve the error

EXCEPTION HANDLING CONSTRUCT

Its just like if else


consider the following code

int main ( )

int a=0, b=5, c ;

try {

if ( b==0 )

throw 101 ;

c=a/b ;

cout<<c ;

catch ( int e )

{ cout<<"division by zero, error code"<<e ;

}}

to yahan "try" mei koi chizcheck krne ko kahega vo, agr satisfactory h kaam to neeche jo throw likha h it
wont get executed and instead execute c=a/b and cout but if it aint satisfactory, this 101 will be thrown
and catch ( int e) ll catch it. basically in this case, it ll catch the integer e.

But why catch throw when you could have used if else??

its bcoz if else "returns" stuff.. essentially it returns answer however in certain cases hmei answer return
hi ni krna we just simply have to say that iska koi answer nhi h basically example consider the following
code

int division ( int a, int b)


{

if (b!=0)

return a/b ;

else

return ____

int main ( )

int x=10, y=0, z ;

try {

z=division (x,y) ;

cout<<z<<endl ;

catch ( int e )

cout<<"division by zero error code"<<e ;

this code will give an error because in the division function's body, there are two returns, i.e two answers
jbki we want one exception and one answer, so instead of writing

if (b!=0)

return a/b ;

else

return ____
we will write

if(b==0)

throw 1 ;

return a/b ;

so basically throw and catch serves as communication between two functions

** in above example code we were throwing integer value but we can throw anything like float double
character etc. you can even throw an object of a class or the class itself

We can have multiple try statements i.e multiple things to try

also, un multiple statements mei b more than one statements can be unsatisfactory hence more than
one throws are possible isliye more than one catch blocks are also possible

catch (...) [ three dots]

this s called "catch all" block and can catch all type of throws i.e a catch block for all type of exceptions.

separate exceptions k liye separate catch blocks hi use krne chahiye bcoz they give exact and clear
messages to the user

usinga catch all block means ki different type of exceptions k liye user ll get same message which isnt
preferred

**catch all bock if you have to write then it must be written below all the other catch blocks kyunki agr
oopr hi likh diya then vahi catch krlega sbhi exceptions ko aur neeche vale block kuch pdkdenge hi nhi
** nesting of try and catch blocks can be done

** suppose there are two classes one of them is inheriting from th eother one, so when you will write
the same "try" statement code for both classes and two catch blocks will be made then, pehle child class
ka catch bnega uske baad parent ka.

TEMPLATE FUNCTIONS

1. When the same function can work for different type of data types

below is a a template funnction for finding the maximum of two variables x and y

template <class T>

T maximum ( T x, T y )

return x>y?x:y ;

2. The function can take different types of arguments. below is a function which can add an integer T to a
double R.

template < class T, class R>

void add( T x, R y)

cout<<x+y ;

TEMPLATE CLASSES

These are also like template functions

suppos you have to make stacks for different data types so instead of making different stack classes for
different data types, we can make a single stack class ( generalized) which will make stacks for all the
data types.

template <class T>

class stack

private :

T S[10] ; ( array S of data type T which can be any data type )

int top ; ( top pointer, ye to int type ka hi hoga bcoz pointer assigned h ek place ko)

public :

void push ( T x) ;

T pop ( ); ( push and pop functions working on data type T )

};

now we will give the body of those functions outside the class

template < class T >

void stack<T> : : push( T x)

_________ body}

tmplate <class T >

T stack<T> : : pop ( )

{_______ body }
CONSTANT qualifier

if you write the keyword "const" before a declaring a variable then it becomes a constant. uske baad us
function ya class mei the value of that varible cant be changed.

if you want that variable to be globally constant, then you have to write following

# define x 10

where x is the variable and 10 is the fixture

difference between this method and using the constant qualifier is that

ye jo define method h ye code se pehle likha ja with # include files

its called a pre processor directive and it is performed before the compilation process starts. it wont eat
any memory whereas constant qualifier will take some memory. define method is just a symbolic
constant.

2nd usage of constantt--> constant pointers

so this means that the pointer can access and read the data but cannot modify that data

example

int main ( ) {

int x=10 ;

int *ptr=&x ;

++*ptr ; ( using ptr to increment value of x so x becomes 11)

but instead of this second last line we write, const int *ptr=&x ;

then the value of x wont get incremented to 11. it will just be accessed and read by the pointer.

the above line can also be written as int const *ptr=&x ;

** basically vo jo pointer hoga it can point to any data but it cant be used to change that data.
3rd usage-->

what if you write int *const ptr=&x ;

this time the pointer itself gets constant i.e once you have assigned an address to that pointer, it cant
point to any other address now. however it can be use dto increment or decrement that data

4th usage-->

writing const int*const ptr=&x ;

this time the pointer is locked on the address as well as the value, i.e neither can it be used to access
another address now nor can it be used to change the data to which it is pointing

CONSTANT keyword in functions ( used after the function declaring)

class demo {

public :

int x=10 ;

int y=20 ;

void display ( ) const

x++; }

here, the compiler will show an error and tell us that value of x cant be changed but aapne glti se change
krdi h while writing the function.

( jb tu x++ krega tb data member ki value b change hojaegi oopr int x=10 mei and we dont want that.

so if you want a function to only read a member then you can use this method.)

5th usage-->

while using call by reference, i.e ( when same variable ka ek aur naam ho.
call by reference functiuons are used to make a function, an inline function.)

void fun( int &x, int &y)

x++ ;

cout<<x<<y ;

int main( )

int a=10, b=20 ;

fun (a,b) ;

( here, x and y are nothing but a and b. [ literally ]. its the same memory block as we have used the "&".

now jb hum ye code chlaenge tb it will incerement x and 10 ki jgh 11 hojaega original data member bhi.
so to avoid that we will just use the keyword "const" while calling by reference.

i.e in the baove example, first line mei hum likhenge

void fun(const int &x, int&y)

PREPROCESSOR DIRECTIVES / DIRECTIVES

basically, compilation start hone se pehle we define things.

example

#define PI 3.14

basically ye oopr vali line ll replace PI with 3.14 in all of the code you will write in below. These are
known as symbolic constants.

This can be applie dto functions too. for example,


# define sqr(x) (x*x)

ab jb tu neeche code likhega aur argument dega function mei suppose 5. then it will be replaced by 5*5.
( whole function ll be replaced by x*x)

#define msg(x) #x

yahan tune jb neeche msg ko argument dega hello then it will convert it into a string.. ( remember, aese
string k liye double qoutes use krne pdte hain)

now consider the following syntax

# ifndef

# define _______ ( blank jgh pr whatever you wanna define)

# endif

what this ll do is ki agr jo blank jgh pr tune chiz define kri h, vo code mei define nhi krta coder, tbhiu
define hogi is method se, otherwise nhi.

NAMESPACES

used to remove name conflict. example in case you are writing multiple different functions of same
name which arent overloaded or even of same class.

example, consider a piece of code with two fuctions of name fun. one gives output "prashant" and
second gives "rizul"

now, aese to complier compile hi ni krega error aega but we can bypass that and use both the functions
by using namespace.

to do that, enclose the whole function inside a namespace exmaple


name space first

void fun()

cout<<"Prashant" ;

similarly, doosri function ko namespace second mei enclose kr skta h and while calling them, simply say

int main ) {

first : : fun( ) ;

similarly, second one k liye second : : fun( )

aur agr ye nhi krna to simply use "using namespace first ;"

fir iske neeche u can use first function aur by chance second use krna ho to vo scope resoultion se
second vale ko use krlena

DESTRUCTORS

Just like how constructors are used to initialize objects, usi tarah, destructors are used in the end (means,
written in the end of class) taki vo objects jo memory and other resources lere vo na lein ek bar unka
kaam khtm ho gya to. so jb function end, destructor deallocates the resources.

name of the desctuctor is the same as that of the constructor. bs itna h ki its written after a tilde sign ( ~)

class test {
public :

test ( )

cout<<"test created" ; }

___

____

~test ( )

{ cout<<"test destroyed " ;

};

main ( )

test *p=new test ( ) ; [ dynamically allocating

delete p ; [dynamically bnaya h to delete bhi kna pdega]

yahan pr jb delete p call hoga tb destructor function test will be called.

jb hum normal functions vgera likhta h ( no dynamic memory allocation) tb unhe jo memory allocate hoti
h vo stack mei hoti h but DMA mei heap mei hoti h. destructor automatically delete krdeta h bina kisi
additional instruction k when theres no DMA but in case of DMA, alag se instruction deni pdegi delete ki
and then the destructor ll do its work.

order of calling of destructors in case of inheritance

consider a base class car and a derived class innova aur un dono me i apne apne constructor aur
destructor bhi diye hain.

now we already know that jb derived class innova ka koi object bnaya jaega tb pehle, constructor of base
class ll be called, then constructor of innova ll be called, uske baad jb function end ho jaega...

destructor of derived class innova ll be called and then destructor of base class car ll be called.

Now suppose you are using a base class pointer to access a derived class object.

class base {

public :

base ( ) {

________ }

~base ( )

{ _______ }

};

class derived : : public base

public :

derived ( ) {

_____ }

~ deived ( ) {

________ }

};

int main ( )
base *p=new derived ( ) ;

delete p ;

now according to theprevious point, while calling this delete command, pehle derived's destructor
should be calle and then base's but in this case, asa nhi hoga.

since you are using a base pointer to call the derived object, so basicallyt vo jo pointer used h vo base
class ka hi h isliye seedhe aur sirf base class ka hi destructor call hoga.

now whats the problem with this?

Isse, base class ne jo resources le rkhi hain vo to free hojaegi but derived class ki nhi ho paegi since uska
destructor never got called

so to avoid this, we can use the keyword "virtual" while making the base classe's destructor i.e

virtual~base( )

isse, derived class ka destructor aur base class ka bhi, dono execute honge.

** base class pointer to derived class object is used to achieve run time polymorphism.

STREAMS

our program interacts. it takes input from user, gives output on monitors, similarly, it access files on the
system etc.

so streams are use for that interaction. they are nothing, but contain classes which further contain
objects

example,

IOS i.e input output stream which contains istream class of which cin is an object of, iostream is
responsible for outputs

isi tarah files se interaction k liye b classes hoti hain

like ifstream and ofstream ( input file stream and output file stream)
FILE HANDLING...

1. Writing in a file

#include <fstream>

int main ( ) {

ofstream outfile( "my.txt")

outfile<<"hello" ;

outfile.close ( ) ;

this will store the material( hello in this case) in a file named my.txt on your system. if a file doesnt exist
of this name, then it will be created automataically.

now iske do mode hote hain

append (app) ismei the data stored already is not deleted and the new data is added

truncate ( trunc) this is the by defuat and means that the data stored in that target file is deleted and
then the new data is stored

to apply append mode write this in place of last line

ofstream outfile("my.txt", ios: : app)

here, ios is a node

** last mei its important to close the resource being used. in this case, the file my.txt is being used. now
suppose ki koi pendrive us file ko use kr rha h and you ask the pdrive to eject so it will refuse to do so
becoz the OS knows that its using some resource on the system.

** remember that ofstream is a class responsible if you want to write in a file. also, "outfile" is just an
object of this class you can name it anything.
2. Reading from a file

now first, off remember ki ismei the file you are reading from should exist, not like the last case
( obviously)

suppose you wanna read from file my.txt containing a string hello and integer 25.

#include<fstream>

int main ( )

ifstream infile ; [ object creation]

infile.open("my.txt") ;

string str ;

int x ;

infile>>str ;

infile>> x ;

this ll simply read data from the file but in case the file doesnt exist you can display a message,

( continuing the previous code)

if (!infile)

cout<<"file not opened" ;

or you can also write


if(! infile.is_open( ) )

cout<<"file not opened" ;

but but but, its also important to tell when the end of the file has come, so in the end write..

if(infile.eof( ) )<< "end of file reached" ; [eof-end of file]

infile.close ( ) [ yahan b close krna is important ]

SERIALIZATION

The process of storing and retrieving the state of an object.

Consider this code

$include<iostream>

#include<fstream>

using namespace std ;

class student

public :

string name ;

int roll ;

string branch ;

};

int main ( )

student s1 ;
s1.name="john" ; s1.roll=10 ; s1.branch="CS" ;

ofstream ofs ("Student.txt", ios : :trunc ) ;

ofs<<s1.name<<endl ;

ofs<<s1.roll<<endl ;

ofs<<s1.branch<<endl ;

now, we already know that this code ll save john, 10, CS in a file named student.txt.

but rather than typing shit likes.name, s1.roll etc, whgat if we could type it as a whole object.

this is called serialization

for this, we ll have to overload the operator <<

and for overloading we use friend function, so above code becomes...

using namespace std ;

class student

public :

string name ;

int roll ;

string branch ;

friend ofstream & operator<< (ofstream &ofs, student &s ) ;

};

ofstream & operator<< (ofstream &ofs, student &s)

{
ofs<<s.name<<endl ;

ofs<<s1.roll<<endl ;

ofs<<s1.branch<<endl ;

return ofs ;

int main ( )

student s1 ;

s1.name="john" ; s1.roll=10 ; s1.branch="CS" ;

ofstream ofs ("Student.txt", ios : : trunc ) ;

ofs<<s1 ;

ofs.close( ) ;

now lets see the same thing in case you need to retrieve data froma file. in this case we ll use the input
file stream, and we need to overload the extraction operator

( we are gonna perform retrieval for the same data which we entered and from the same file that we
made in the last section)

using namespace std ;

class student

public :

string name ;
int roll ;

string branch ;

friend ofstream & operator<< (ofstream &ofs, student &s ) ;

friend ifstream & operator>> (ifstream &ifs, student &s) ;

};

ifstream & operator>> (ifstream &ifs, student &s)

ifs>>s.name>>s.roll>s.branch ;

return ifs ;

ofstream & operator<< (ofstream &ofs, student &s)

ofs<<s.name<<endl ;

ofs<<s1.roll<<endl ;

ofs<<s1.branch<<endl ;

return ofs ;

int main ( )

student s1 ;

s1.name="john" ; s1.roll=10 ; s1.branch="CS" ;

ofstream ofs ("Student.txt", ios : : trunc ) ;


ofs<<s1 ;

ofs.close( ) ;

ifstream ifs ("student.txt" ) ;

ifs>>s1 ;

ifs.close ( ) ;

**make sure ki overloading k time object reference i.e &s hi use kro or the object wont get updated.

TWO TYPES OF FILES

1. Text files ( human readable)

2. Binary files (machine readable)

example, binary form of x=23 is

0000000000010111

which is nothing but binary conversion of 23.

and text form of same variable is 00110010 00110011

where 00110010 is the binary form of 50 and 00110011 is binary form of 51

and where 50 is the ascii code for 2 and 51 is the ascii code for 3.

(also, ascii code to binary is represented in 8 bits thats why there are additional 2 zeroes in the front of
each segment)

now, if you wanna read write from on a text file, you can use the process told in the previous function,
but if you want to read or write from or on a binary file, the in fstream class there is a mode that has to
be used ( binary mode)

aur usmei aage read ( ) and write ( ) functions can be used to read o9r write binary data

ios : ; binary

read ( )

write ( )

** also, binary is fast and takes less space in comparision to text.

MANIPULATORS

used to enhance or formatting strings

example, in polace of \n, we use endl to give line break., so here, endl is a manipulator as its helping in
formatting

some more manipulators are

hex, oct, dec ( for integers)

they display respective forms of an integer

example

cout<<hex<<163 ; will display hexadecimal form of 163.

fixed, set( ), left, right, WS

cout<<fixed<<125.731 ; prints the e exavt decimal value of this integer

cout<<set(10)<<"hello" ; displays hello o occupying 10 places


cout<<hello<<WS<<prashant ; separates these strings by a wide space

aur b kafi hote hain look on your own.

STL (Standard Template Library)

a library containing several classes which help us to write code easily and make things less comples for us

three parts

1. algorithms ( contain algorithms which can be applied on containers)

2. contrainers ( set of data)

3. iterators ( helps in traversing through that data)

some commonly used containers are

1. vector

essentially an array jismei you can add delte insert elements without hassle unlike a normal array

(( you cant add an element to front of vector)

2. list- a double linked list

3. forward list- a normal linked list

4. deque- like a vector but ismei front m b element enter kr skte hain

5. priority queue- always delete the largest elemt

6. stack

7.t- contains only unique elements


8.multi set- uniqueness not necessary

9. ap-used to stoe key value pairs. each elemt has a unique key

exmaple 1 "john" is a key value pair of 1 and john

this is used in hash tables

10. multi map- elements can have same key but no two pairs can be same

( detail mei pdhna pdega alag se this isnt enough)

HOW TO USE CONTAINERS

lets take an example of vector

#include <vector> [ including header file for container]

main ( ) {

vector <int> v={ 10,20,40,90} ; [<int> tells vector what input type is being given. and the rest is
initialization. you can give the size too by v( size). vector is a class here ]

v.push_back (25) ; ( adds 25 at the end of vector )

v.pop_back ( ) ; ( deleted last element from vector)

ITERATION or traversal

vector<int> : : iterator itr=v.begin( ) ;

where iterator is a class which belongs to the vector class, itr is an object of iterator class
and itr=v.begin ( ) is simply giving that iterator to the stated vector. so its basically assigning the iterator.

begin ( ) is a function.

this function is present in all stl classes. similarly theres also a function called end( ).. r.begin ( ) r.end( )
etc also exist

now, to traverese thru the given vector above, simply write..

for ( itr=v.begin( ) ; itr!=v.end( ) ; itr++ )

cout<<*itr ;

( this itr works just like a pointer thats why we useds *it instead of just itr. using this pointer method you
ll be able to modify the original value in the vector. i.e, able to perform both read and write and thus
proving that it works like a pointer.)

**interseting part--> agr vector ki jagah list use krni h then simply replace the word vector in header file,
instead of vector class, use list class and in traversal statement, use list instead of vector word. simple.
similarly you can do with other type of containers. but different containers might ve different functions
to insert deleteetc. data so take care of that.

we can aloso do the iteration by using "for each" loop

for( int x: v)

cout<<x ;

C++ 11

1. AUTO keyword- use this when you dont know the output type
example..

auto x=2*5.7 + 'a' ;

2. Suppose you have an integer x of type int now if you wanna give the same data type to varible y then
you can do it by...

decltype(x) z=12

FINAL keyword

use 1.

class parent final

( when you type this, i.e while declaring a class, the word final will prohibit this class from doing
inheritance, i.e you cant derive classes from parent class now

use 2.

final functions of parent class cant be overriden in child class

** only virtual functions can be made final

SMART POINTERS

But why smart pointers?

jb normal pointers use krte heap memory allocation k liye, tb kbhi kbhi we forget to deallocate the
memory and that causes memory leaks and big problems.

isliye cpp 11 provides smart pointers jo function over hote hi us memory ko already free kr dete

there are three types of smart pointers

1. unique_ptr

fun ( )
{

unique_ptr<rectangle> p1 (new Rectangle (10,5) ) ; }

here, p1 is a smart pointer of type unique_ptr. it belongs to class rectanle and is making an object new
rectangle with parameters 10 and 5 of the same class, rectangle.

**an object can have only one unique pointer

2. shared_ptr

as the name suggests, an object can have multiple pointers pointing to it and those pointers are called
shared pointers

these pointers maintain a reference counter ( basically keeps the count ki total pointers hain point krre
us object ko)

3. weak_ptr

just like shared ptr but it doesnt maintain a refernce counter

**literal- value you assign to a avariable

You might also like