C
C
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
3.linking library- machine code for commands like cout, cin etc. etc.. the librarries contain the code for
these
code section- this is where the OS brings the code from HDD.)
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"
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
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
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
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
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
** whenever you are declaring a char variable and assigning it a value, use quotes example-
2. no space in between
OPERATORS
list of operators-
1. Arithematic
2.Relational
3.Logical
4.Bitwise
5.Increment/decrement
6.Assignment
associativity- if the code gets executed from left to right or right to left
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>)
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-
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)
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)
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.
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;
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
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>
int main() {
return 0;
example code
#include<iostream>
int main(){
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
https://www.udemy.com/course/cpp-deep-dive/learn/lecture/10961438#notes
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.
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-
if(true) {
int c=a+b;
cout<<c;
SWITCH CASE
lets learn it directly from an example
int day = 4;
switch (day) {
case 6:
break;
case 7:
break;
default:
[ 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.
}
PRACTICE LOOPS KAFI ACHE SE THEY ARE IMPORTANT TO MAKE GRIP ON THE LANGUAGE
ARRAYS
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.
A[8,6,3,9,7,4]
{ cout<<A [i]; }
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;
int A[ ], n=10, 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
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.
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}
two types of variables - data variables nd address variables. ( its obvious by the names what they are)
( 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.
cout<<x ll display 10
cout<<&x = 200/201
cout<<p = 200/201
cout<<&p= 300/301
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
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*p;
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++
2. p--
yk
3.p=p+2
yk
5. d=p-q
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.
3.Dangling pointer
REFERENCE
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
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. ]
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] ;
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) ;
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-
cout<<s1 ;
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" ;
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--
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.
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" ;
7. string to long- strtol(str1,null, base) this is used to convert a string into long integer.
base- depends on the no. system, if using decimal use 8, binary=2, octa=8 and so on.
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.
{ here, ; and = are the chosen deriemeters jinke around k token u want, u can change these delimeters
according to your choice.}
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 )
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
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.
cin>>str; ( ll only take characters jbtk beech mei space nhi h. i.e for hello world, only hello ll b takem)
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( );
cout<< s.capacity ( ) ;
4. s.max_size( ) gives you the max capacity for that object. depnds on the compiler
cout<<str.max_size ( ) ;
str.clear ( ) ;
string str="hello" ;
if ( str.empty ( ) )
else
example
string s="hello" ;
s.append ("bye") ;
cout<<s ;
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.
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
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
** 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"
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.
(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
e.g, you can change holiday to holimay by command str[ 4 ]= 'm' ; but not by using at( ) operator.
string str2="world"
cout<< str1 ;
if instead of concatenation, u type str1=str2; ( this line ll copy contents of str2 to the str 1)88888888888
and cout<<str1 ;
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
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.
it ll print "today".
( u must unerstand that iterator kinda plays like a pointer here sou gotta dereference it by using * while
giving cout.
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.
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.
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..
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-->
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
int z ;
z=x+y ;
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.
example
return x+y ; }
return x+y+z ;
void main( )
yahan ye dono functions are basically same. ..( same names just differet argument list) this is called
function overloading.
now here, remember.
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.
T max( T x, T y )
if(x>y)
return x ;
else return y;
main ( )
int c= max(10,5) ;
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.
return (x + y + z + w);
// Driver Code
int main()
// Statement 1
// Statement 2
// Statement 3
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.
int temp;
x = y; /* put y into x */
return;
}
Now, let us call the function swap() by passing actual values as in the following example −
#include <iostream>
// function declaration
int main () {
int a = 100;
int b = 200;
swap(a, b);
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.
int temp;
return;
}
// function declaration
int main () {
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;
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.
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.
int temp;
x = y; /* put y into x */
return;
}
let us call the function swap() by passing values by reference as in the following example −
// function declaration
int main () {
int a = 100;
int b = 200;
swap(a, b);
RETURN BY ADDRESS
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
int main( )
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
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.
for example,
if ( n>0)
cout<<n<<endl ;
fun ( n-1 ) ;
here, the function fun is callling itslef again and again just the value inside is modified.
POINTER TO A FUNCTION
void display ( )
cout<<"hello" ;
}
int main ( )
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.
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.
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.
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
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
[
public : ( access specifier. by default class k andr ka maal is not accessible)
int length ;
return length*breadth ;
void main ( )
r1. breadth=5 ;
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.
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
in main function,
int main ( )
p-> length=10 ; ( using a pointer to access data member length) here, -> is the dereferncing operator.
void main ( )
rectangle *p
DATA HIDING
Data members should always be private and member functions should be public
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)
class rectangle
private :
int length ;
int breadth ;
public :
length=l ;
breadth=b ;
return length ;
}
{
return breadth ;
};
CONSTRUCTORS IN CPP
A constructor is a special member function with same name as that of the class
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
There can be many constructors in a class. It can be overloaded but it can not be inherited or virtual
class rectange
private :
int length ;
int breadth ;
public :
length=0 ;
breadth=0 ;
}
2. Paramaterized constructor ( takes arguments ) ( you want a volvo xc90 )
class rectange
private :
int length ;
int breadth ;
public :
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 ( )
yahan p
agr firse zrurt pde constructors pdhne ki then watch this video
https://www.youtube.com/watch?v=hAA8FBq2bA4
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 ]
accessors
mutators
argumented constctors
copy constructors
facilitators ( functions like calculating area and primeter... i.r which actually do something )
destructors
If you write all these functions in a class then that class is known as a perfect class
SCOPE RESOLUTION OPERATOR ( : : )
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.
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.
int Rectangle : : Area ( ) ( oprator se pehle you have to write class name)
};
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.
class A {
int a ;
public :
{ this->a = a ;
a = a1 ;
so this pointer is just helping us by saving us from the ambiguity of variable names.
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.
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
main ( )
complex c1 (3, 7)
complex c2 ( 5, 4 )
complex c3 ;
class complex {
private :
int real ;
int img ;
public :
};
{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.
you must know that cin is a predifened object of istream class and cout is a predfined object of ostream
class.
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
#include<iostream>
#include<cstudio>
class stu {
int id;
public :
[ 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)
}
friend void operator << (ostream &out, stu &s )
out<<"name="<< s.name ;
void main ( )
stu s ;
cout<< s;
INHERITANCE
class rectangle
{
privatte :
int llength ;
int breadth;
public :
int getlength ( ) ;
int getbreadth ( ) ;
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 ( ) ;
int volume ( )
};
int main ( ) {
cuboid c ( 10,5,3) ;
cout<<c.volume( ) ;
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
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.
..... }
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.
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
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
TYPES OF INHERITANCE
Single
multilevel
WAYS OF INHERITANCE
publicly
prviately ( by default)
protectedly
1.class parent ;
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.
1.class parent ;
child ll ve access to both piblic and protected and they ll be saved in that format only
1.class parent ;
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.
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.
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 ;
};
public :
void fun2 ( )
cout<<"fun2 of derived"<<endl ;
};
int main ( )
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" ;
};
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.
purpose-- to force the child classes to override the parent classes's virtual function.. i.e to achieve
polymorphism]
ABSTRACT CLASSES
** 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 :
void fun( )
{ cout<<"derived fun" ;
}};
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:
b) A global function
class test
private : int a ;
protected : int b ;
pulic : int c ;
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
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 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 :
test ( ) ( constructor )
a=10 ;
b=10
cout ++ ;
};
main ( ) ;
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
** 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
** static members can be accessed using objects or they can also be accessed directly using class name.
but the thing to be remembered is that these functions can only access static data members and not non
static members.
return count ;
INNER/NESTED CLASSES
a nested class is a class jiske andr ek aur class likhi jaye which is useeful for that main class
class outer {
public :
int a ;
static int b ;
void fun ( )
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 )
** 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)
outer : : inner i ;
EXCEPTION HANDLING ; a feature of OOP
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.
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 exception handling --> telling the user exactly what is the problem and then giving him guidelines to
resolve the error
int main ( )
try {
if ( b==0 )
throw 101 ;
c=a/b ;
cout<<c ;
catch ( int 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
if (b!=0)
return a/b ;
else
return ____
int main ( )
try {
z=division (x,y) ;
cout<<z<<endl ;
catch ( int 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 ;
** 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
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
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
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.
void add( T x, R y)
cout<<x+y ;
TEMPLATE CLASSES
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.
class stack
private :
int top ; ( top pointer, ye to int type ka hi hoga bcoz pointer assigned h ek place ko)
public :
void push ( T x) ;
};
now we will give the body of those functions outside the class
_________ body}
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
difference between this method and using the constant qualifier is that
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.
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 ;
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.
** basically vo jo pointer hoga it can point to any data but it cant be used to change that data.
3rd usage-->
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-->
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
class demo {
public :
int x=10 ;
int y=20 ;
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.)
x++ ;
cout<<x<<y ;
int main( )
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.
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.
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)
# ifndef
# 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.
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( ) ;
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 ( )
};
main ( )
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.
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 ( )
{ _______ }
};
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.
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
like ifstream and ofstream ( input file stream and output file stream)
FILE HANDLING...
1. Writing in a file
#include <fstream>
int main ( ) {
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.
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
** 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 ( )
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,
if (!infile)
but but but, its also important to tell when the end of the file has come, so in the end write..
SERIALIZATION
$include<iostream>
#include<fstream>
class student
public :
string name ;
int roll ;
string branch ;
};
int main ( )
student s1 ;
s1.name="john" ; s1.roll=10 ; s1.branch="CS" ;
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.
class student
public :
string name ;
int roll ;
string branch ;
};
{
ofs<<s.name<<endl ;
ofs<<s1.roll<<endl ;
ofs<<s1.branch<<endl ;
return ofs ;
int main ( )
student s1 ;
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)
class student
public :
string name ;
int roll ;
string branch ;
};
ifs>>s.name>>s.roll>s.branch ;
return ifs ;
ofs<<s.name<<endl ;
ofs<<s1.roll<<endl ;
ofs<<s1.branch<<endl ;
return ofs ;
int main ( )
student s1 ;
ofs.close( ) ;
ifs>>s1 ;
ifs.close ( ) ;
**make sure ki overloading k time object reference i.e &s hi use kro or the object wont get updated.
0000000000010111
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 ( )
MANIPULATORS
example, in polace of \n, we use endl to give line break., so here, endl is a manipulator as its helping in
formatting
example
a library containing several classes which help us to write code easily and make things less comples for us
three parts
1. vector
essentially an array jismei you can add delte insert elements without hassle unlike a normal array
4. deque- like a vector but ismei front m b element enter kr skte hain
6. stack
9. ap-used to stoe key value pairs. each elemt has a unique key
10. multi map- elements can have same key but no two pairs can be same
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 ]
ITERATION or traversal
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
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.
for( int x: v)
cout<<x ;
C++ 11
1. AUTO keyword- use this when you dont know the output type
example..
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.
( 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.
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
1. unique_ptr
fun ( )
{
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.
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