100% found this document useful (1 vote)
189 views117 pages

C++ Tevhnical Paper Presentation With Some Changes

This document provides an introduction to C++ and discusses some key concepts: 1) C++ programs can be structured in a procedure-oriented or object-oriented way, with the latter emphasizing data over procedures and providing features like inheritance and polymorphism. 2) The compilation process involves preprocessing, compilation, and linking. Compilation errors occur during compilation and linker errors during linking if references are not resolved. 3) C++ supports basic data types like int, char, float and reference variables. Keywords, variables, and operators are also introduced. 4) The document discusses control structures like loops and conditions that allow repeating blocks of code or executing code conditionally.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
189 views117 pages

C++ Tevhnical Paper Presentation With Some Changes

This document provides an introduction to C++ and discusses some key concepts: 1) C++ programs can be structured in a procedure-oriented or object-oriented way, with the latter emphasizing data over procedures and providing features like inheritance and polymorphism. 2) The compilation process involves preprocessing, compilation, and linking. Compilation errors occur during compilation and linker errors during linking if references are not resolved. 3) C++ supports basic data types like int, char, float and reference variables. Keywords, variables, and operators are also introduced. 4) The document discusses control structures like loops and conditions that allow repeating blocks of code or executing code conditionally.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 117

INTRODUCTION TO C++

Structure of procedure-oriented programs

main

fun1

fun2

fun3

fun4

fun5

fun6
Employs top-down approach

Structure of object-oriented programs


Object A Object B
Data members

Data members

Member function

Member function

Object C

Data members

Member function

Employs bottom-top approach

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

Provides concept of overloading of functions and operator &


inheritances which improves scope of program.

//First C++ program #include<iostream.h>

A Simple C++ Program structure


//Preprocessor directive

int main() //Function { cout<<Welcome to C++; return 0; }

Comments

Comment are used in C++ programs for documentation so that it can be readable or understandable by other programmer. All comments are ignored By compiler and have no effects on the way by the program runs. It may appear anywhere in program. 1)Single line comments: Any sentence after the double slash(//) is called single line comments. It is only for that particular line. Note: It is additional feature of C++ not availabel in C. 2)Multiple line comments: It starts with delimiters /* and ends with */ covers multiple lines. /*Welcome to C++ C++ is better as compared to C*/

Preprocessor directives
Lines in the program that begins with # are known as Preprocessor
Directives

The preprocessor is a program that creates modified version of the


C++ 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 seen the effect of this already with the #include directive. This instructs the preprocessor to find the file whose name follows the #include directive, and to write it into the intermediate file at that location. whereas every statement should end with a semicolon. #define, #if etc.

The preprocessor directives should not end with semicolon(;) Example #include<stdio.h>

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 at


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

Compilation Process [V.IMP]


.h This is when compile errors can occur! Processed Source Preprocessor
#directives processed

Compilation Phase
.cpp

Object File .obj

Compiler

Linking Phase

All references must be resolved!


Else, linker errors occur!

Parsing Static type checking Declarations Needed Code generation Optimizations

.obj
Object files to be linked

Linker

.exe
Executable File

Libraries You Requested

Standard Library

Startup Module

Program Creation
*.h Files *.h Files Pre-Processor *.cpp File *.cpp File Compiler

Object File

Object File

Linker

Static Library

Note: A Static Library is a collection of object files

Executable

DATA TYPES & OPERATORS

Output Operator cout<<Welocme to OOPS; This statement causes string to be displayed on screen It is predefined object that represents the standard output stream in C++ The operator is called as insertion or put to operator. The bitwise left shift operator in C is overloaded << with cout object. No need to specify data types,as in C [Advantage] Cascading of insertion operator If we want to display more than one variables we can cascade insertion operator. char name[10];int rno; cout<<Name is<<a<<Roll no<<rno;

OPERATOR

When cascade the operator,the values of the variables E.g


assigned from right to left
int a=1; cout<<a<< <<++a<< <<<<a++; Output:3 3 1 & not ( 1 2 2 )

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] char name[10]; int ,rno; cin>>name>>rno;

Cascading of input operator

cin reads only one word.

Note while receiving string care should be taken about space bcoz
it act as string terminator.

#include<iomanip.h> 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.

Manipulators

endl It is output stream manipulator which creates new line wherever it is placed. Its effect is same as newline character (\n). cout<<Welcome<<endl<<To C++; Output: Welcome To C++

setw It is used to set width space the spacing between the fields. It is more advantageous to use setw as compare to tab character(\t) which by The value is right justified cout<<Name<<setw(5)<<name<<endl;
cout<<RollNo<<setw(5)<<rno<<endl; Output: Name abc Roll No 1 default set the spacing between the fields by default of 8 bytes.

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<<setprecision(1)<<x; Output x=3.0

Keywords These are the special words, which is designed to do a specific task and

DATA TYPES

whose meaning is already know to compiler. Since it is predefined keyword, it cannot be used as identifiers. These words are also know as reserved words. 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

Identifiers : Name of variables, symbolic constants, functions,arrays,classes are called


as identifiers. The predefined identifiers are known as keywords.

Variables

In C++ a variable is a place to store information. A variable is a location in


your computer's memory in which you can store a value and from which you can later retrieve that value.

Naming a variable Because you can have many variables in a single program, you
must assign names to them to keep track of them. Variable names are unique. If two variables have the same name, C++ would not know to which you referred when you request one of them. characters. Their names must begin with a letter of the alphabet but, after the first letter, they can contain letters, numbers, and underscore ( _ ) characters.

Variable names can be as short as a single letter or as long as 32

Uppercase and lowercase are distinct and variables are case sensitive

Some C++ variable types.

Declaration Name
char unsigned char signed char int unsigned int signed int short int unsigned short int signed short int long long int signed long int unsigned long int float double long double

Type

Character Unsigned character Signed character (same as char) Integer Unsigned integer Signed integer (same as int) Short integer Unsigned short integer Signed short integer (same as short int) Long integer Long integer (same as long) Signed long integer (same as long int) Unsigned long integer Floating-point Double floating-point Long double floating-point

Determing size of variables type cout << "The size of an int is:\t\t" << sizeof(int) << " bytes.\n"; cout << "The size of a short int is:\t"<< sizeof(short) << " bytes.\n"; cout << "The size of a long int is:\t" << sizeof(long) << " bytes.\n"; cout << "The size of a char is:\t\t" << sizeof(char) << " bytes.\n"; cout << "The size of a float is:\t\t" << sizeof(float) << " bytes.\n"; cout << "The size of a double is:\t" << sizeof(double) << " bytes.\n";
Output: The size of an int is: The size of a short int is: The size of a long int is: The size of a char is: The size of a float is: The size of a double is: 2 bytes. 2 bytes. 4 bytes. 1 bytes. 4 bytes. 8 bytes.

Dynamic initializations of variables


C++ permits initializations of variables at run times. This is referred to as
dynamic initializations of variables at run times.

Dynamic initializations of variables is extensively used in object-oriented


programming. We can create exactly type of object needed, using the information known at run time.

e.g. int a=strlen(string); float avg=tot/n;

Thus both declarations and initializations can be done simultaneously at the


place where the variable is used for the first time.

Reference Variables
A reference variable is an alternative name for a variable. A shortcut. A reference variable must be initialized to reference another 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; int total=100; int &sum=total;

E.g.

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

CONTROL STATEMENTS

The Concept of Loops You use the loop concept in everyday life. Any time you have to repeat the
same procedure, you are performing a loopjust as your computer does with 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 test condition 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

Condition is any C++ expression, and statement is any valid C++

statement or block of statements. When condition evaluates to TRUE (1), statement is executed, and then condition is tested again. This continues until condition tests FALSE, at which time the while loop terminates and execution continues on the first line below statement. // count to 10 int x = 0; while (x < 10) cout << X: " << x++; More Complicated while Statements

E.g.

The condition tested by a while loop can be as complex as any legal C++
expression. This can include expressions produced using the logical && (AND), || (OR), and ! (NOT) operators. is a somewhat more complicated while statement.

WAPC++ to compute +1/2+3/4+5/6+..+99/100 using while loop float sum=0; int i=1,j=2; while(i<=99 && j<=100) //complex while loop using logical AND { i=i+2; j=j+2; sum=sum+ i/j; } cout<<sum; Using while Loop: Ex No 1: WAPC++ to print odd numbers from 0-50 Ex No 2: WAPC++ to sum up the following series -1+2-4+8-16+..1024.

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 dowhile loop. General form of do-while loop is do { 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<=100); getch(); }

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 is
for( 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 loop If there is semicolon after the for loop then the loop is said to be a software delay or do nothing for loop for(i=0;i<100;i++); Also by using comma operator, more than one variable an be initialised as seen below for(i=1,j=1;i<=10;i++,j++)

WAPC++ to find factorial of given number


void main() { int i, fact,n; cout<<\n Enter number whose factorial is to be found; cin>>n; for(i=1 ,fact =1;i<n;i++) fact=fact*i; cout<<\n Factorial of number is :<<fact; getch(); }

WAPC++ program to compute fibonacci series.


void main() { clrscr(); int a,b,c,n; a=0;b=1; cout<<"Enter number of terms :"; cin>>n; cout<<Fibonacci series is ; cout<<"\t"<<a<<"\t"<<b;; for(int i=0;i<(n-2);i++) { c=a+b; cout<<"\t"<<c; a=b; b=c; } getch();

Using for loop. Ex No 1


1 2 3 4 5 2 3 3 4 4 4 5 5 5 5

Ex No 2 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Ex No 4 (Pascals triangle) 1 1 2 1 1 3 3 1 1 4 6 4 1

Ex No 3(Flyod triangle) 1 2 3 4 5 6 7 8 9 10 Ex No 5 WAPC++ for finding sine value.

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 nature of 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<<X is superior to Y; Here the test expression is evaluated first. It returns true statement followed by it, is executed;if it returns false,then the control is transferred to the next statement.

Block if statement Here block of group of statements follow the test expression. The
general form is if (test expressions) { statements; } e.g.

if( physics >=40 && chemistry>=40 && maths>=40) { cout<<Pass in exam; ave=(float)tot /3.0; cout<<Average is %f :ave; }

If the test expression returns false then the control is transferred to next statement after the brackets.

Nested if statement
This is the most important aspect of if statement in the sense it may lead
to confusion if not properly used general form of nested if is,

The nested if is a statement that is the object of either if or else. The


if( test expression) { statements; } else if( test expression) { statements; } else { statements; } The above is known as if-else ladder

To find sales commission using nested if construct


void main() { float sales, com; cout<<Enter sales value:; cin>>sales; if( sales<=1000) com=0; else if( sales<=2000) com=sales*0.50; else if( sales<=5000) com=sales*0.08; else com=sales*0.10; }

Switch statements [Selection Statements Or Conditional statements] 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 particular case and causes exit from switch statement, transferring control outside switch.

The default is optional statement is executed if no matches are found.

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 a force return to the operating system. Because of this property this is used 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. When a break statement is encountered, the loop is immediately exited and the program continues with the statement immediately following the loop. The general form is ,

while( test expression) { if something; break; } Continue Unlike break statement which cause the loop to be terminated the continue statement causes the loop to be continued with the next iterations after skipping the statements in between, thus by passing the rest of loop .

The general form is


for(exp1;exp2;exp3) { if something continue; } e.g. for(i=0;i<5;i++) { cin>>no; if(no<0) continue;

goto

This is an unconditional statement. The goto statement may be

used to exit from several layers of nesting. The goto requires a label for operations and the label must be in the same function as the goto that uses.

The syntax is label:


label:

//declaration syntax //Calling

goto label;

goto label;

NOTE:The use of goto is highly discouraged since more gotomeans more confusion.

ARRAYS & STRINGS

An array is a collection of data storage locations, each of which holds the

ARRAYS

same type of data. Each storage location is called an element of the array The statement int 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 a nonnegative 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.

One dimensional array This is also called as list. This means that an item in an array can be Some basic operations performed on a one-dimensional array are:

accessed by just giving one subscript form of a single-dimension array is type specifier identifier-name [size] 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.

Using 1-D array perform: Ex No 1 WAPC++ to find maximum, minimum number in array and also
determine 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 one
of size n.

Ex No 5 WAPC++ that removes repeated element repeated element and


display it only once e.g. {1,2,2,3,4} => {1,2,3,4}

Two dimensional array A two dimensional array in fact, is an array of one dimensional array. A single The general format is

dimensional array can store a list of values, whereas two dimensional array can store a table of values.It is also called as matrix type specifier array_name[rowsize][colsize];

In two dimensional array also, element declaration (both in row and column) is done with zero origin subscripting.

Array Initialization Similar to one dimensional array, two dimensional array can also be initialized by following 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};

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 of


conformable matrices.

#include<string.h> String is defined as array of character It is terminated by null character \0. The general form of string declarations is char string-name [size]; e.g.char name[20]; char address[30]; Because of null character must be equal to one plus maximum numbers character .

CHARACTER ARRAY

Array initializations char name[5]={t,s,e,c,\0 }; Char a[ ] ={ h,i\0};


Reading strings scanf(%s, name); cin>>name

Here a is array of three character

it reads till it encounters a blank character to overcome this difficulty we have similar function called gets( ) which reads the string until terminated by enter key. gets(name);

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: EX No 1 WAPC++ to read a string and output ASCII value of each
character.

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

FUNCTIONS

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, each module is considered as a function. type specifier function-name (argument list) argument declarations { body of function; return( expression); }

The general form of function is

e.g.

int add( int a ,int b) { return(a+b); }

Functions Parameters The parameters are local variables inside 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 function
are 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 body of a
compound statement (a block): { int block; }//variables is destroyed after function block

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 is declared

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. Global variables are static by default Calling a function

Pass by value
The content of variables is copied to the formal parameters of the function
definition, 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 called
function but does not get in return unless the called function returns value.

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 is reflected in the caller function. Pass by value Pass by reference void swap(int a, int b) void swap(int &a, int &b) { { int t=a; int t=a; a=b; a=b; b=t; b=t; } } main() { int a=1,b=2; swap(a,b); }
main() { int a=1,b=2; swap(a,b); }

Passing array in function

Like variables array can also be passed through function the syntax is return type function_name(data type array-name[size]) //Declaration of function 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); }

int int int int

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. add(int x); add (int x, int y); add (int x, int y, float z); 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 Functions can call themselves! This is called recursion. Recursion is very useful its often very simple to express a
complicated 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 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.

STRUCTURES

Structure A Structure is a container, it is collection of data items or variables

of different data types that is referenced under the same name. It provides 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 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};

struct stud
name rno

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 variable must 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 of structures begin their indexing at 0.

Ex No 2 WACP++ to accept the data for 10 employees.

Structure initializations 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

{ char name[10]; int rno; struct date dt; }; Ex no 3 WAPC++ to maintain student database and sort in ascending order of roll no.

Structures and Function When a structure element is passed to a function it is actually

passing 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); display(s.rno);

//Passing name //Passing roll no

POINTERS

It is a variable which stores address of another variable. In other word, if

Pointers

one variable contain the address of another, then the first variable is said to point 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 are referred to as pointers to void

Null Pointers The null pointer is a special constant which is used to explicitly

indicate that a pointer does not point anywhere NULL is defined in the standard library <cstdlib> (or <stdlib.h>) In diagrams, indicated as one of:

NULL

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 address of a variable with the & operator
Address

MEMORY

int *x , y; y = 123; x = &y;

0 1 2 3 4 5

123

...

...

Pointers to anything int *x; int **y; y x some int

some *int

some int

double *z;
z some double

Pointers and Array


An array name is basically a const pointer. You can use the [] operator with a pointer:
Note x=a // gives base address of array i.e a[0] => x=&a[0]; x is the address of a[2]
int *x; int a[10]; x = &a[2]; for (int i=0;i<3;i++) x[i]++;

x[i] is the same as a[i+2]

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

*(ptr+2)

*(ptr+4)

a[0]

a[1]

a[2]

a[3]

a[4]

int *ptr = a;

int a[5];

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

C' S' 'I'

\0

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

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->name p->rno Note p-> is another way of writing s[0]

CLASSES AND OBJECTS

Classes extend the built-in capabilities of C++ to assist you in representing


and solving complex, real-world problems.

CLASSES AND OBJECTS

Class.

Class is a user define data type


A class is just a collection of variables-often of different types-combined
with a set of related functions

A class enables you to encapsulate, or bundle, these various parts and


various 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 the declaration with a closing brace and a semicolon. { int value; };

class base

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 more


functions

The declaration of object is shown below

An object created is built in type variable. Once the class has been
declared, we can create a variable of that type using the class name. base bobj;

Access Control An access control defines a boundary to a member of the class. They are
also 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 the

class .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 access the 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 (to
other classes and functions that may access variables of your class type). the interface.

The implementation of your class doesn't matter outside the class only

Class members 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 a class. Data members are classified into two groups

Regular (auto) Static Member Functions A function that is defined inside a class declaration is called as

member function . In general all members are defined in the public area of the class It can also be defined in the private area .Member functions are also called as methods.

Definitions of functions Defining inside class stud


Defining outside class stud { char name[10]; int rno; public: void getdata(); void putdata(); };//End of class void stud:: getdata() { cin>>name>>rno; } void stud :: putdata() { cout<<name<<rno; } void main() { stud s; s.getdata(); s.putdata(); }

{ char name[10]; int rno;

public: void getdata() { cin>>name>>rno; } void putdata() { cout<<name<<rno; } };//End of class

void main() { stud s; s.getdata(); s.putdata(); }

Inline Functions An inline function is a function that is expanded inline when it is invoked 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 a function as inline or not.

(called). That is compiler, replaces with the corresponding function code.

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 A friend function is non-member function, which has access to


private and protected data of class.

Characteristics of friend function Friend functions are declared explicitly in the body of class preceded
by keyword friend. Usually friend function are declared in public section, but it can be declared 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 functions It is possible to have a single variable that is shared by all instances
of a class (all the objects). By declaring the variable as static. of the class. at global or file scope.

Data members that are static must be declared and initialize outside 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 are created. 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 static


members is that the static members has scope whereas global variables do not.

Static member functions 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 of member functions exist in memory. All the object share the same copy of the member functions through a pointer called this .This pointer contains the address of the object through which function is being invoked. The

E.g. void putdata()


{

compiler automatically generates the pointer when an object is created

cout<<this->name; cout<<this->rno; }

CONSTRUCTOR DESTRUCTOR

Constructor A constructor is a special member function whose task is to initialize the


objects 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 return values. 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 no


parameters. complex c;

NOTE: When constructors are defined explicitly ,the default constructor must be always be defined. Otherwise we cannot create an object without parameters.

Parameterized constructor We can initialized the data members of an object when they are

created. This can be achieved through passing arguments to constructor 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 the object of the class to which it belongs. But it can accept a reference of an object of class as parameter. [Copy constructor]

Copy constructors When an object of the class is used to initialized another object,

C++ perform a bitwise copy. That is an identical copy of the source object 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 an argument .The process of initializations is called as copy initializations

complex(complex &x)
{ real=x.real; img=x.img; }

complex c1(1,2); complex c2(c1); complex c3=c1;

//Calling of copy constructor ////Calling of copy constructor

Constructor with default arguments Initializing the formal parameters is called as default argument. Like

functions, 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); complex(int x=0) { { } } Here both the constructor can be called with no parameters. Hence complex c1; will generate error of ambuguity.

NOTE complex()

ALL DEFAULT CONSTRUCTOR MUST BE INITIALIZED FROM LEFT TO RIGHT

Destructors
A destructor is a special member function that is implicitly called to
destroy 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()


{ }

INHERITANCE

CONCEPT OF INHERITANCE

Polygon

Rectangl e

Triangle

Inheritance is concept by which the properties of one class are avialabel to another.It allows new classes to built from older classes, instead of being re-written.

Member acess specifier Two levels of access control over class members
class definition inheritance typpe

The general syntax is class DerivedClassName : access-level BaseClassName


where access-level specifies the type of derivation private by default, or public

base class/ superclass/ parent class


members goes to

derived class/ subclass/ child class

derive from

Access Rights of Derived Classes


The type of inheritance defines the access level for the members of derived class that are inherited from the base class

Type of Inheritance

private private
protected

protected protected

public protected

Access Control for Members

private

public

private

protected

public

FORMS OF INHERITANCE
Single Inheritance
A

FORMS OF INHERITANCE
Multilevel Inheritance
A

FORMS OF INHERITANCE
Multiple Inheritance

FORMS OF INHERITANCE
Hierarchical Inheritance
B

d1

d2

d3

d4

FORMS OF INHERITANCE
Hybrid Inheritance
Base

d1

d2

d3

MULTIPLE INHERITANCE AMBIGUITY


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


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 helping in solving problem

OPERATOR OVERLOADING

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

Restrictions on operators
Operators that can be overloaded
+ ~ /= <<= -new[] ! %= == ->* delete[] * = ^= != , / < &= <= -> % > |= >= [] ^ += << && () & -= >> || new | *= >>= ++ 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 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 or protected members of that class are accessed directly.

Overloading unary operators

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;
When compiler sees postincrementing expression, such as d1++; Generates the member-function call d1.operator++( 0 ); Prototype: Date::operator++( int );

Postfix versions

Overloaded binary operators

Non-static member function, one argument Non-member function, two arguments

class String { public: string operator + (string s2); }; // end class String y += z; equivalent to y.operator+=( z );

SIMPLE SINGLE LINKED LIST

Use of linked list One of the main drawback of array is that size of array cannot be increased

or decreased during run time. Dynamic memory allocation concepts find very useful in cases where we do not 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 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

node

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.

head

//

INSERTION AT BEGINING New head

1Hea
d

head

//

INSERTION AT MIDDLE

//

INSERTION AT END

//

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.

head

//

DELETION OF HEAD

head head

//

DELETION OF MIDDLE

head

48

17

142

//

DELETION OF END

head

48

17

142

//

You might also like