of 117
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
1/117
INTRODUCTION TO C++
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
2/117
fun1
fun5
fun2
fun4
fun6
fun3
Structure of procedure-oriented programs
main
Employs top-down approach
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
3/117
Structure of object-oriented programs
Data membersData members
Data members
Member function
Member function
Member function
Object A Object B
Object C
Employs bottom-top approach
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
4/117
Advantages of C++ over C
New data and functions can be added easily.
Programs are divided into objects rather than smaller functions.
Emphasis on data rather than procedures.
Provides data hiding i.e. data cannot be accessed by externalfunction.
Provides concept of overloading of functions and operator &inheritances which improves scope of program.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
5/117
A Simple C++ Program structure//First C++ program#include //Preprocessor directive
int main() //Function{cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
6/117
Preprocessor directives
Lines in the program that begins with # are known as PreprocessorDirectives
The preprocessor is a program that creates modified version of theC++ source program according to directives supplied.
The compiler does not read your original source code file; it reads
the output of the preprocessor and compiles that file. You've seenthe effect of this already with the #include directive. This instructsthe preprocessor to find the file whose name follows the #includedirective, and to write it into the intermediate file at that location.
The preprocessor directives should not end with semicolon(;)
whereas every statement should end with a semicolon.
Example #include#define, #if etc.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
7/117
Functions(main) A function is self-contained block of statements that performs the desired
task.
Object oriented programs consists of mostly classes but there is always atleast one C like function main().
The execution of a program begins with main() and it ends at closing brace
{ }
The int value returned by main( ) is value returned to the operating system.
If the value returned is 0,it is the message to system that the program has
completed successfully.
If it is non zero then it is abnormal termination of program. NOTE:The default data type of main (and all function in C++) is
int
main(){ }
will give warning.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
8/117
Compilation Process [V.IMP]
.cpp
.h
Preprocessor
Processed Source
Compiler#directives processed
ParsingStatic type checking
Declarations NeededCode generationOptimizations
.obj
Object File
CompilationPhase
LinkingPhase
.obj
Object files to be linked
Libraries YouRequested
StandardLibrary
StartupModule
Linker .exe
ExecutableFile
All referencesmust be resolved!
Else, linker errors occur!
This is whencompile errors can occur!
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
9/117
Program Creation
*.cpp File
Pre-Processor
*.h Files
Compiler
*.cpp File
*.h Files
Object FileStatic Library
Linker
Object File
ExecutableNote: A Static Library is a collection of object files
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
10/117
DATA TYPES & OPERATORS
OPERATOR
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
11/117
OPERATOR Output Operator cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
12/117
Input Operator int x; cin>>x; The number we entered will be stored in the memory location of x. cin is object of class istream. The class istream is associated with the standard input device (i.e.
keyboard) (console i/p). The bitwise right shift operator in C is overloaded >> with cin object. No need to specify data types,as in C [Advantage]
Cascading of input operatorchar name[10];int ,rno;cin>>name>>rno;
cin reads only one word.
Note while receiving string care should be taken about space bcozit act as string terminator.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
13/117
Manipulators #include The standard library provides set of functions for manipulating the input and
output. These functions are called as manipulators.
Manipulators are operators that are used to format the data display. The most commonly used ones are endl, setw.
endl It is output stream manipulator which creates new line wherever it is placed. Its effect is same as newline character (\n).
cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
14/117
setprecision It is used to reduces decimal points to specified values. Most of compiler round the values. General syntax for setprecision is
float x=2.999
cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
15/117
DATA TYPES Keywords These are the special words, which is designed to do a specific task and
whose meaning is already know to compiler. Since it is predefined keyword,it cannot be used as identifiers. These words are also know as reservedwords. Many of them are common to both C & C++.
Few of them are given below.asm do for protected
auto double friend public
bool default goto register
break delete if return
case else inline
char enum long
class float new
const false operator
continue int private
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
16/117
Identifiers :
Name of variables, symbolic constants, functions,arrays,classes are calledas identifiers. The predefined identifiers are known as keywords.
Variables
In C++ a variable is a place to store information. A variable is a location inyour computer's memory in which you can store a value and from whichyou can later retrieve that value.
Naming a variable
Because you can have many variables in a single program, youmust assign names to them to keep track of them. Variable names areunique. If two variables have the same name, C++ would not know to
which you referred when you request one of them.
Variable names can be as short as a single letter or as long as 32characters. Their names must begin with a letter of the alphabet but,after the first letter, they can contain letters, numbers, and underscore( _ ) characters.
Uppercase and lowercase are distinct and variables are case sensitive
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
17/117
Some C++ variable types. Declaration Name Type char Character unsigned char Unsigned character
signed char Signed character (same as char) int Integer unsigned int Unsigned integer signed int Signed integer (same as int) short int Short integer unsigned short int Unsigned short integer
signed short int Signed short integer (same as short int) long Long integer long int Long integer (same as long) signed long int Signed long integer (same as long int) unsigned long int Unsigned long integer float Floating-point
double Double floating-point long double Long double floating-point
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
18/117
Determing size of variables type cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
19/117
Dynamic initializations of variables
C++ permits initializations of variables at run times. This is referred to asdynamic initializations of variables at run times.
Dynamic initializations of variables is extensively used in object-orientedprogramming. We can create exactly type of object needed, using theinformation known at run time.
e.g. int a=strlen(string);
float avg=tot/n;
Thus both declarations and initializations can be done simultaneously at theplace where the variable is used for the first time.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
20/117
Reference Variables
A reference variable is an alternative name for a variable. Ashortcut. A reference variable must be initialized to referenceanother variable. Once the reference is initialized you can treat it just like any other variable. The general form is
data type &reference-name =variable-name;
E.g.int total=100;int &sum=total;
Reference variables must be initialized at the time of declarations.
Both variable refer to same data object in memory.
NOTE: Here & is not address operator it means reference to int
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
21/117
CONTROL STATEMENTS
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
22/117
The Concept of Loops
You use the loop concept in everyday life. Any time you have to repeat thesame procedure, you are performing a loopjust as your computer doeswith the while statement.
While Loop [Sequential Control Statements] It is an entry controlled loop i.e. test condition is evaluated and if it is true
the body of loop is evaluated. This process is repeated until the testcondition becomes false.
General form of while is
while( test expression){Sequence of statement;}
NOTE:while(1)
{}will cause infinite loop and requires certain unconditional
statement to exit loop
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
23/117
Condition is any C++ expression, and statement is any valid C++
statement or block of statements. When condition evaluates to TRUE (1),statementis executed, and then condition is tested again.
This continues until condition tests FALSE, at which timethe while loop terminates and execution continues on the first linebelow statement.
E.g.// count to 10
int x = 0;while (x < 10)cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
24/117
WAPC++ to compute +1/2+3/4+5/6+..+99/100 using while loop
float sum=0;int i=1,j=2;
while(i
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
25/117
Do-while loop [Sequential Control Statements]
On some occasion it may be necessary to execute the body of the loop,before the test is performed. Such an occasion can be handled using do-while loop.
General form of do-while loop isdo{sequence of statements;}while(test expressions) ; [NOTE]
WAPC++ to find sum of odd numbers between 1& 100.
void main(){int i=1,sum=0;do{sum=sum+i;
i=i+2;}while(i
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
26/117
For Loop [Iterative Control Statements]
It is iterative control loop. It is used when no of iterations are known as compile time itself.
The general form of for loop isfor( expression 1,expression 2,expression 3){sequence of statements;
}Here expression 1 is the initial value.
expression 2 is the testing value.expression 3 is the increment (step) value.Note there is no semmicolon after the for loop.
Time delay for loopIf there is semicolon after the for loop then the loop is said to be a
software delay or do nothing for loopfor(i=0;i
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
27/117
WAPC++ to find factorial of given numbervoid main()
{
int i, fact,n;coutn;
for(i=1 ,fact =1;i
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
28/117
WAPC++ program to compute fibonacci series.
void main(){clrscr();
int a,b,c,n;a=0;b=1;coutn;cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
29/117
Using for loop. Ex No 1 Ex No 2
1 1
2 2 1 2
3 3 3 1 2 3
4 4 4 4 1 2 3 4
5 5 5 5 5 1 2 3 4 5
Ex No 3(Flyod triangle) Ex No 4 (Pascals triangle)
1 1
2 3 1 2 1
4 5 6 1 3 3 1
7 8 9 10 1 4 6 4 1
Ex No 5
WAPC++ for finding sine value.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
30/117
IF Statement[ Selection Statements Or Conditional statements] This is one of the powerful conditional statement. The if statement can be
used in different can be used in different forms, depending upon the natureof the conditional test, and the main forms are:
Simple if Block if Nested if
Simple if The general form of simple statement is
if (test expression)
----------------;
e.g.
if(x>y)
cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
31/117
Block if statement Here block of group of statements follow the test expression. The
general form isif (test expressions)
{statements;}e.g.
if( physics >=40 && chemistry>=40 && maths>=40)
{cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
32/117
Nested if statement
This is the most important aspect of if statement in the sense it may leadto confusion if not properly used
The nested if is a statement that is the object of either if or else. Thegeneral form of nested if is,
if( test expression){
statements;}else if( test expression){statements;}
else{statements;}
The above is known as if-else ladder
T fi d l i i i t d if t t
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
33/117
To find sales commission using nestedif construct
void main()
{
float sales, com;
coutsales;
if( sales
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
34/117
[ ] This is multiple branching control statement , and this one is very useful
for decision making when more than one case is involved.
The general form of switch statements is switch(choice)
{case label 1:sequence statements.;break;
case label 2:sequence statements.;break;..default:statement sequence;
}//End of switch
break statement at end of each block , indicates the end of the particularcase and causes exit from switch statement, transferring control outsideswitch.
The default is optional statement is executed if no matches are found.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
35/117
Exit , Break, Continue, Goto [Jump Control Statements]
Exit The exit function causes immediate termination of the entire
program .This function stops the program execution and causes aforce return to the operating system. Because of this property this isused only for specific purposes.main(){if something
exit(1);}
Here if something is true, then the program terminates.
Break
An early exit from the loop is possible by a break statement. Whena breakstatement is encountered, the loop is immediately exited and theprogram continues with the statement immediately following theloop. The general form is ,
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
36/117
while( test expression)
{
if something;
break;
}
Continue
Unlike break statement which cause the loop to be terminated thecontinue statement causes the loop to be continued with the nextiterations after skipping the statements in between, thus by passing the
rest of loop .
The general form isfor(exp1;exp2;exp3)
{
if something continue;}
e.g. for(i=0;i>no;
if(no
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
37/117
goto
This is an unconditional statement. The goto statement may beused to
exit from several layers of nesting. The goto requires a label foroperations and the label must be in the same function as the gotothat uses.
The syntax is
label: //declaration syntax
goto label; //Calling
NOTE:The use of goto is highly discouraged since moregotomeans more confusion.
label:
goto label;
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
38/117
ARRAYS & STRINGS
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
39/117
ARRAYS An array is a collection of data storage locations, each of which holds the
same type of data. Each storage location is called an element of the array
The statementint num[5];
declares an array num of 5 components of the type int
The components are num[0], num[1], num[2], num[3], and num[4].
The general form of accessing an array component is:array_name[indexExp];
where indexExp, called index, is any expression whose value is anonnegative integer
Index value specifies the position of the component in the array.
The [ ] operator is called the array subscripting operator. The array index always starts at 0.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
40/117
One dimensional array This is also called as list. This means that an item in an array can be
accessed by just giving one subscript form of a single-dimension array istype specifier identifier-name [size]
Some basic operations performed on a one-dimensional array are: Initialize Input data Output data stored in an array Find the largest and/or smallest element
Each operation requires ability to step through the elements of the array
Easily accomplished by a loop E.g. int age[10],float marks[10],char name[10]
Array Initialization int a[5]={1,2,3,4,5}; float a[5]={1.1,2.2,3.2,4.5,5.6}; int b[ ]={1,1,2,2} In the last one size has been omitted and have been declared as an array
with 4 elements compiler automatically sizeof array.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
41/117
U i 1 D f
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
42/117
Using 1-D array perform:
Ex No 1 WAPC++ to find maximum, minimum number in array and alsodetermine its location.
Ex No 2 WAPC++ to sort an array of size 10.
Ex No 3 WAPC++ to compute fibonacci series.
Ex No 4 WAPC++ to merge two array first one of size m and second oneof size n.
Ex No 5 WAPC++ that removes repeated element repeated element anddisplay it only once
e.g. {1,2,2,3,4} => {1,2,3,4}
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
43/117
Two dimensional array A two dimensional array in fact, is an array of one dimensional array. A single
dimensional array can store a list of values, whereas two dimensional array canstore a table of values.It is also called as matrix
The general format istype specifier array_name[rowsize][colsize];
In two dimensional array also, element declaration (both in row and column) isdone with zero origin subscripting.
Array Initialization
Similar to one dimensional array, two dimensional array can also be initialized byfollowing their declarations with a list of initial values enclosed in braces.
e.g.int a[2][3]={1,1,1,2,2,2,}; //First row initialized to 1 and second row to 2
This can also be written as
int a[2][3]={1,1,1 },{2,2,2};
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
44/117
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
45/117
Using 2D array perform following:
Ex No 1 WAPC++ for two dimensional array of 3*3 (matrix) to find
following Sum of all elements Row wise sum Column wise sum Sum of main diagonal
Sum of off diagonal
EX No 2 WAPC++ to perform matrix addition, subtraction, multiplication ofconformable matrices.
CHARACTER ARRAY
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
46/117
CHARACTER ARRAY #include String is defined as array of character It is terminated by null character \0.
The general form of string declarations ischar string-name [size];e.g.char name[20];char address[30];
Because of null character must be equal to one plus maximum numberscharacter .
Array initializations char name[5]={t,s,e,c,\0 }; Char a[ ] ={ h,i\0};
Here a is array of three character
Reading strings scanf(%s, name); cin>>name
it reads till it encounters a blank characterto overcome this difficulty we have similar function called gets( ) which
reads the string until terminated by enter key.
gets(name);
Writing strings
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
47/117
Writing strings printf(%s,name); Similar to printf function we have puts() and putchar( ) function
to write character.
String Handling Function
strcat(s1,s2) Concatenates (combines) s2 into s1
Using string handling perform:
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
48/117
Using string handling perform:
EX No 1 WAPC++ to read a string and output ASCII value of eachcharacter.
EX No 2 WAPC++ to count number of es in a given string
EX No 3 WAPC++ for sorting names
EX No 4 WAPC++ to check whether given string is palindrome or not.
EX No 5 WAPC++ to delete all es present in string.e.g. tsec => tsc
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
49/117
FUNCTIONS
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
50/117
Functions A function is considered as fundamental building block of the language. In
order to avoid complexity of a program while coding ,debugging and testing,the program is divided into functional parts or subprograms thus, eachmodule is considered as a function.
The general form of function istype specifier function-name (argument list)argument declarations{body of function;return( expression);
}
e.g. int add( int a ,int b){return(a+b);
}
Functions Parameters
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
51/117
Functions Parameters The parameters are local variablesinside the body of the function. When the function is called they will have the values passed in.
Local Variables Parameters and variables declared inside the definition of a functionare local.
They only exist inside the function body. Once the function returns, the variables no longer exist!
Block variables You can also declare variables that exist only within the bodyof a
compound statement (a block):{int block;
}//variables is destroyed after function block
Global variables
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
52/117
Global variables You can declare variables outside of any function definition these
variables are global variables. Any function can access/change global variables.
Scope of variables The scope of a variable is the portion of a program where the variable has
meaning (where it exists). A global variable has global (unlimited) scope. A local variables scope is restricted to the function that declares the
variable.
A block variables scope is restricted to the block in which the variable isdeclared
Storage Class auto created each time the block in which they exist is entered. register same as auto, but tells the compiler to make as fast as
possible. static created only once, even if it is a local variable. extern global variable declared elsewhere.
Local variables are auto by default
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
53/117
Local variables are auto by default. Global variables are static by default
Calling a function
Pass by value
The content of variables is copied to the formal parameters of the functiondefinition, thus preserving the contents of the arguments in the calling
funtion.
The information flows only in one way i.e. caller sends the valued to calledfunction but does not get in return unless the called function returns value.
Pass by Reference
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
54/117
Pass by Reference
The formal parameter becomes reference to argument. The information flows in two way i.e. even if the calling function
does not return a value, the changes made in the variable isreflected in the caller function.Pass by value Pass by referencevoid swap(int a, int b){int t=a;
a=b;b=t;}
main()
{int a=1,b=2;swap(a,b);}
void swap(int &a, int &b)
{
int t=a;
a=b;
b=t;
}
main()
{
int a=1,b=2;
swap(a,b);
}
Passing array in function
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
55/117
g yLike variables array can also be passed through function the syntax is
return type function_name(data type array-name[size]) //Declaration offunction
functionname(array name) //Calling of function
Note in declaration the size of array not know can be skipped just by declaring[ ] i.e array_name[ ]
Array name can be same or different
e.g.
int max(int a[ ] ){.}
main (){int a[5]={1,1,2,3,4},big;big=max(a);}
Function Overloading
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
56/117
Function Overloading Overloading is bothing but use of same thing for different purposes. Overloaded operators a specific case of overloading General: select specific method/operator based on name, number, and type
of arguments
E.g.int add(int x);
int add (int x, int y);
int add (int x, int y, float z);
int add (double x, double y);
Rules for overloading of functions
All the functions have same name but with different sets of parameter.
The return type can be same or different.
Ambiguous definitions of functions should be avoided.
Recursive Function
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
57/117
Functions can call themselves! This is called recursion.
Recursion is very usefulits often very simple to express acomplicated computation recursively.
Most common example to explain recursion is:int factorial( int x )
{
if (x == 1)
return(1);else
return(x * factorial(x-1));
}
Let say to find factorial of 3 then
3*fact(2)3*2(fact(1)
3*2*1
=>Factorial of 3=6
Using functions perform
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
58/117
Using functions perform
EX No 1 WAPC++ to find maximum number in array
EX No 2 WAPC++ to find fibonacci series using recursive function.
EX No 3 WAPC++ to find GCD using recursive function.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
59/117
STRUCTURES
Structure A Structure is a container it is collection of data items or variables
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
60/117
A Structure is a container, it is collection of data items or variablesof different data types that is referenced under the same name. Itprovides convenient means of keeping related information together.
Structures are used to organize related data (variables) in to a nice
neat package.
The general form of struct is,struct tag-name
{data type members;};
The tag-name identifies the particular structure and its type specifier.The field that comprise the structure are called the structure elements
Accessing members in structure You can treat the members of a struct just like variables. You need to use the member access operator '.' (pronounced
"dot").
Initialization of structure
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
61/117
a a o o u u
Structure variable can also be initialized. struct stud
{
char name[10];int rno;
};
stud ={ABC,01};
struct stud{
char name[10];
int rno;
};
stud s1 ={PQR,11};
stud s2 ={XYZ,12};name
rno
struct stud
Ex No 1 WACP++ to initialize members in a structure
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
62/117
Ex No 1 WACP++ to initialize members in a structure.
Array of structure The most common use of structure is array of structure. To define an array
of structures, first the structure must be defined and then the array variablemust be declared.
e.g.struct stud s[10];
This creates 10 set of variables that are organised as defined in the
structure stud .It must be remember here that like all variable, array ofstructures begin their indexing at 0.
Ex No 2 WACP++ to accept the data for 10 employees.
Structure initializations
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
63/117
You can use structures just like variables:
struct stud
{char name[10];int rno;
};
struct stud s1,s2;s1.name = ABC";
s2 = s1;Above statement will initialize s2.name=ABC
Nested structure struct date
{int d,m,y;
};
struct stud
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
64/117
{char name[10];int rno;
struct date dt;} ;
Ex no 3 WAPC++ to maintain student database and sort inascending order of roll no.
Structures and Function
When a structure element is passed to a function it is actuallypassing the value of that element to the function.
The general format of passing a structure to the called function is function name (structure variable name);
e.g stud s; //Object of stud display(s.name); //Passing name display(s.rno); //Passing roll no
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
65/117
POINTERS
Pointers
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
66/117
It is a variable which stores address of another variable. In other word, ifone variable contain the address of another, then the first variable is said topoint to the second.
Generic Pointers Sometimes we need to use pointer variables that arent associated with
a specific data type
In C++, these pointers simply hold a memory address, and arereferred to as pointers to void
Null Pointers The null pointeris a special constant which is used to explicitly
indicate that a pointer does not point anywhere
NULL is defined in the standard library (or )
In diagrams, indicated as one of:
NULL .
int *x;
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
67/117
int x; x is a pointer to an integer. You can use the integer x points to in a C++ expression like this:
y = *x + 17;
*x = *x +1;
In C++ you can get the addressof a variable with the & operator
.
.
.
.
.
.
MEMORY
0
1
23
4
5
Address
123
int *x , y;y = 123;x = &y;
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
68/117
int *x;
int **y;
double *z;
x some int
Pointers to anything
y some *int some int
z some double
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
69/117
Pointers and Array
An array name is basically a constpointer. You can use the [] operator with a pointer:
Note x=a // gives base address of array i.e a[0] => x=&a[0];
int *x;
int a[10];
x = &a[2];
for (int i=0;i
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
70/117
Pointer arithmetic
Integer math operations can be used with pointers. If you increment a pointer, it will be increased by the size of whatever it
points to.
a[0] a[1] a[2] a[3] a[4]
*ptr *(ptr+2) *(ptr+4)
int a[5];int *ptr = a;
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
71/117
Pointer Parameters
Pointers are passed by value (the value of a pointer is the address it holds).
If we change what the pointer points to the caller will see the change.
If we change the pointer itself, the caller won't see the change (we get a
copy of the pointer)Pointers and String
A string is a null terminated array of characters. null terminated means there is a character at the end of the the
array that has the value 0 (null). Pointers are often used with strings:char *str = CSI;
C' S' 'I' \0
str
WAPC++ t t t i l th i i t
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
72/117
WAPC++ to compute string length using pointers.
void main()
{char str[20],*ch;
int i=0;
printf(\nEnter string);
scanf(%s,str);
ch=str; //Assign base address i.e. ch=&str[0];while(*ch!=\0)
{
i++; //incrementing count
ch++; //Incrementing pointer
}printf(\n Length of string is %d :,i);
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
73/117
Structure and pointers C++ permits pointers to structures, just as they allowed to any
other type of variables . Structure pointers are declared by placing * in front of structure variables name. E.g. struct stud *s; Consider the following declaration struct stud
{
char name[10];int rno;}s[2],*p;p=s would assign the base address i.e. p will point to s[0].
Member can be accessed using arrow operator ( ->)
p->namep->rno
Note p-> is another way of writing s[0]
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
74/117
CLASSES AND OBJECTS
CLASSES AND OBJECTS
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
75/117
CLASSES AND OBJECTS Classes extend the built-in capabilities of C++ to assist you in representing
and solving complex, real-world problems.
Class.
Class is a user define data type
A class is just a collection of variables-often of different types-combinedwith a set of related functions
A class enables you to encapsulate, or bundle, these various parts andvarious functions into one collection, which is called an object.
To declare a class, use the class keyword followed by an opening brace,and then list the data members and methods of that class. End thedeclaration with a closing brace and a semicolon.
class base{int value;};
OBJECTS
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
76/117
OBJECTS Objects are instance of class
Memory is created only when objects are declared.
The fundamental purpose of an object is to provide one or morefunctions
The declaration of object is shown below
An object created is built in type variable. Once the class has beendeclared, we can create a variable of that type using the classname.
base bobj;
Access ControlA t l d fi b d t b f th l Th
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
77/117
An access control defines a boundary to a member of the class. They arealso known as visibility labels and access specifiers .
A class can have three kinds of access control:
Private: Member of a class is accessible only by members and friend of theclass .By default all the members of the class is private. Protected: Member of class is accessible only by members and friends of
the class and members and friends of the derived classes, they can accessthe base member.
Public: Member of class is accessible by everyone.
Data Hiding The interface to a class is the list of public data members and methods.
The interface defines the behavior of the class to the outside world(toother classes and functions that may access variables of your class type).
The implementation of your class doesn't matter outside the class onlythe interface.
Class members
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
78/117
The class can have two kind of members Data members Member functions
Data members All the primary (int, float ,char..) and the secondary data types
(arrays, pointers, structures var,..) can be the data members of aclass.
Data members are classified into two groups
Regular (auto) Static
Member Functions
A function that is defined inside a class declaration is called asmember function . In general all members are defined in the publicarea of the class It can also be defined in the private area .Memberfunctions are also called as methods.
Definitions of functions
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
79/117
Defining inside Defining outside class stud
{
char name[10];int rno;
public:void getdata(){cin>>name>>rno;
}void putdata(){coutrno;
}void stud :: putdata()
{
cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
80/117
An inline function is a function that is expanded inline when it is invoked(called). That is compiler, replaces with the corresponding function code.
The general form of inline function is inline return type function-name (arguments)
{
return.;
}
Depending on the body of function compiler decides whether to keep afunction as inline or not.
Rules for defining inline functions
main() cannot be inline.
If functions are recursive they cannot be inline. If the function contains static variables they cannot be inline.
Advantage Size of object code is considerably reduced. Increase the execution speed
Friend Function
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
81/117
A friend function is non-member function, which has access toprivate and protected data of class.
Characteristics of friend function Friend functions are declared explicitly in the body of class precededby keyword friend.
Usually friend function are declared in public section, but it can bedeclared in private section also.
Friend function called be called with an object, because only data
members can be called with the objects. Friends are not member. One function can be friend of any number of classes.
Disadvantage It is not in scope of class in which it is defined.
It cannot access members name directly. Derived class does not inherit friend function. They may not be declared as static.
Static data members and members functionsIt i ibl t h i l i bl th t i h d b ll i t
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
82/117
It is possible to have a single variable that is shared by all instancesof a class (all the objects). By declaring the variable as static.
Data members that are static must be declared and initialize outsideof the class. at global or file scope.
Characteristics of static data members Static variables are initialized to zero when first object is created, no
other initialization is possible.
There is only one copy of data, no matter how many objects arecreated. Thus all the objects share the same copy of the variable. The general form of declaring it is int class-name:: var-name
NOTE: The difference between global variable and staticmembers is that the static members has scope whereasglobal variables do not.
Static member functions
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
83/117
Like static data members we can also declared member function as static. A static member function can be called using the class name class-name ::function-name();
Static member function can accessed only static data member.
This pointer When an object is created, the object hold only its own copy of the data
members. It does not hold the member function. There is only one copy ofmember functions exist in memory. All the object share the same copy ofthe member functions through a pointer called this .This pointer contains
the address of the object through which function is being invoked. Thecompiler automatically generates the pointer when an object is created
E.g. void putdata()
{cout
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
84/117
CONSTRUCTOR DESTRUCTOR
Constructor A constructor is a special member function whose task is to initialize the
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
85/117
A constructor is a special member function whose task is to initialize theobjects of the class.
The data members can also be initialized through constructors.
Characteristics of constructors They should have same name of class They can de defined either inside or outside the class with scope resolution
operator.
We cannot refer to their address. They do not have return types, even void and therefore cannot returnvalues.
They can have default arguments.
TYPES OF CONSTRUCTORS Default constructor The constructor that accepts no parameters is called as default
constructors. The default constructor of class complex
complex() ----------------Default constructor
{
The default constructor is called when an object is declared with noparameters.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
86/117
pcomplex c;
NOTE: When constructors are defined explicitly ,the default constructor
must be always be defined. Otherwise we cannot create an objectwithout parameters.
Parameterized constructor We can initialized the data members of an object when they are
created. This can be achieved through passing arguments toconstructor functions.The constructors that can take arguments are called as
Parameterized constructor.complex(int x ,int y) --------Parameterized constructor{
real=x;img=y;}
NOTE:The parameter of the constructor can be of any type except theobject of the class to which it belongs. But it can accept a referenceof an object of class as parameter. [Copy constructor]
Copy constructors When an object of the class is used to initialized another object
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
87/117
When an object of the class is used to initialized another object,C++ perform a bitwise copy. That is an identical copy of the sourceobject is created in the target object with the help of constructor.That constructor is called as copy constructor.
A copy constructor takes reference to an object of the class as anargument .The process of initializations is called as copyinitializations
complex(complex &x){
real=x.real;img=x.img;
}
complex c1(1,2);
complex c2(c1); //Calling of copy constructorcomplex c3=c1; ////Calling of copy constructor
Constructor with default arguments Initializing the formal parameters is called as default argument Like
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
88/117
Initializing the formal parameters is called as default argument. Likefunctions, the formal parameters of a constructor can also be initialized.
complex(int r, int im=0){
real=r;imag=im;
} The above constructor can be called with one argument. E.g. complex c1(10);
NOTE complex() complex(int x=0){ {} }
Here both the constructor can be called with no parameters. Hencecomplex c1;will generate error of ambuguity.
ALL DEFAULT CONSTRUCTOR MUST BE INITIALIZED FROM LEFT TORIGHT
Destructors
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
89/117
A destructor is a special member function that is implicitly called todestroy the objects that have been created by constructor.
Destructor has same name as that of class but precedes with tilde(~) sign. Destructor will not have return type not even void. Destructor are called by itself when the object goes outside its
scope. Destructor will not have any return type, not even void.
Destructors are called in the opposite direction of constructors.
Destructor of class complex.
~complex()
{}
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
90/117
INHERITANCE
CONCEPT OF INHERITANCE
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
91/117
Rectangle
Triangle
Polygon
Inheritance is concept by which the properties of oneclass are avialabel to another.It allows new classes to built
from older classes, instead of being re-written.
Member acess specifier
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
92/117
Member acess specifier Two levels of access control over class members
class definition inheritance typpe
The general syntax isclass DerivedClassName : access-level BaseClassName
where access-level specifies the type of derivation
private by default, or public
base class/ superclass/parent class
derived class/ subclass/
child class
derivefrom
memb
ersgoesto
Access Rights of Derived Classes
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
93/117
private protected public
private - - -
protected private protected protected
public private protected public
AccessContro
l
forMembers
Type of Inheritance
The type of inheritance defines the access level for themembers of derived classthat are inherited from the base
class
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
94/117
FORMS OF INHERITANCE
Single Inheritance
A
B
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
95/117
FORMS OF INHERITANCE
Multilevel Inheritance
A
B
C
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
96/117
FORMS OF INHERITANCE
Multiple Inheritance
A B
C
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
97/117
FORMS OF INHERITANCE
Hierarchical Inheritance
d1 d2
B
d4d3
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
98/117
FORMS OF INHERITANCE
Hybrid Inheritance
d 1 d2
Base
d3
MULTIPLE INHERITANCE AMBIGUITY
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
99/117
What happens with duplicate methods?
class base{void draw();};
class derived :public base{void draw() ;};
derived d;d.draw(); // Error: ambiguous
Ambiguity can be resolved explicitly
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
100/117
class base{void draw();
};
class derived :public base{void draw() ;};
derived d;bw.draw(); base::draw() or derived::draw()
Virtual base class can be used.
When base class is declared as virtual only one copy get inherited,thus helpingin solving problem
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
101/117
OPERATOR OVERLOADING
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
102/117
Operator Overloading
Uses of Operator overloading Use traditional operators with user-defined objects Straightforward and natural way to extend C++. It is mechanism which gives additional meaning to the c++ operators. When operator is overloaded, none of its original meanings are lost.
It improves the readability of the code to user and increase the scopeof the operator.
General rules for overloading of operator Only existing operator can be overload. The overloaded operator must have atleast one user-defined operand.
It is not recommended to change the basic meaning of an operator. Operator function can have default argument. All binary overloaded operators must explictily return a value.
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
103/117
Restrictions on operators
Operators that can beoverloaded+ - * / % ^ & |~ ! = < > += -= *=/= %= ^= &= |= >>= [] () new deletenew[] delete[]Fig. 18.1 Operators that can be overloaded.
Arity (number of operands) cannot be changed Unary operators remain unary, and binary operators remain binary
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
104/117
y p y y p y
Operators &, *, + and - each have unary and binary versions
Unary and binary versions can be overloaded separately
No new operators can be created Use only existing operators
Built-in types Cannot overload operators
You cannot change how two integers are added
Operator functions as member functions Leftmost operand must be an object (or reference to an object)of the class If left operand of a different type, operator function must be a
non-member function A non-member operator function must be a friend if private orprotected members of that class are accessed directly.
Overloading unary operators Avoid friend functions and friend classes unless absolutely necessary
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
105/117
Avoid friend functions and friend classes unless absolutely necessary. Use of friends violates the encapsulation of a class. As a member function:
class add {public:void operator + ( )
...};
Pre/post-incrementing/decrementing operators Can be overloaded How does the compiler distinguish between the two? Prefix versions overloaded same as any other prefix unary operator
would be. i.e. d1.operator++();for++d1;
Postfix versions When compiler sees postincrementing expression, such as d1++; Generates the member-function call
d1.operator++( 0 );
Prototype:Date::operator++( int );
Overloaded binary operators
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
106/117
Non-static member function, one argument Non-member function, two arguments
class String {public:string operator + (string s2);}; // end class String
y += z;
equivalent toy.operator+=(z);
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
107/117
SIMPLE SINGLE LINKED LIST
Use of linked listO f th i d b k f i th t i f t b i d
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
108/117
One of the main drawback of array is that size of array cannot be increasedor decreased during run time.
Dynamic memory allocation concepts find very useful in cases where we donot know the exact memory required.
Structural representation of simple singly linked list
A linked list is a series of connected nodes.
Each node contains at least a piece of data (any type).
Pointer points to the next node in the list
Head: pointer to the first node
The last node points to NULL
Operations of List
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
109/117
Insertion: insert a new node at a particular position
Deletion: delete a node with a given value
Display: print all the nodes in the list
Search: find a node with a given value
A
node
I ti d
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
110/117
Inserting a node
Steps Check for insertion at beginning Check for insertion at middle Check for insertion at end Insertion must be in sorted orders as shown.
2 4 6head //
INSERTION AT BEGINING
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
111/117
2 4 6head //
HeadNew head
1
INSERTION AT MIDDLE
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
112/117
2 4 5 //6
INSERTION AT END
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
113/117
2 4 6 //8
Deleting a node
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
114/117
Deleting a node
Steps involved in deletion of a node: Deletion in an empty linked list Head to be deleted. Middle node to be deleted
Last node to be deleted Element not found.
2 4 6head //
DELETION OF HEAD
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
115/117
DELETION OF HEAD
2 4 6head //
head
DELETION OF MIDDLE
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
116/117
DELETION OF MIDDLE
48 17 142head //
DELETION OF END
8/4/2019 c++ Tevhnical Paper Presentation With Some Changes
117/117
DELETION OF END
48 17 142head //