C++ Tevhnical Paper Presentation With Some Changes
C++ Tevhnical Paper Presentation With Some Changes
main
fun1
fun2
fun3
fun4
fun5
fun6
Employs top-down approach
Data members
Member function
Member function
Object C
Data members
Member function
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 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>
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 Phase
.cpp
Compiler
Linking Phase
.obj
Object files to be linked
Linker
.exe
Executable File
Standard Library
Startup Module
Program Creation
*.h Files *.h Files Pre-Processor *.cpp File *.cpp File Compiler
Object File
Object File
Linker
Static Library
Executable
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
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;
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
Variables
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.
Uppercase and lowercase are distinct and variables are case sensitive
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.
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.
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
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.
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
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
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,
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.
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 .
goto
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.
goto label;
goto label;
NOTE:The use of goto is highly discouraged since more gotomeans more confusion.
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].
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.
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
#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
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.
strcat(s1,s2)
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
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); }
e.g.
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); }
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); }
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.
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
of different data types that is referenced under the same name. It provides convenient means of keeping related information together.
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").
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.
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
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.
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);
POINTERS
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
0 1 2 3 4 5
123
...
...
some *int
some int
double *z;
z some double
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)
\0
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]
Class.
class base
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:
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.
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.
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
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
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
cout<<this->name; cout<<this->rno; }
CONSTRUCTOR DESTRUCTOR
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 {
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; }
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()
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.
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
derive from
Type of Inheritance
private private
protected
protected protected
public protected
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
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
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.
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
class String { public: string operator + (string s2); }; // end class String y += z; equivalent to y.operator+=( z );
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.
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
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
//
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
//