cpp latest
TRANSCRIPT
-
8/3/2019 Cpp Latest
1/125
11
Procedure Oriented ProgrammingProcedure Oriented Programming
In the POP approach, theIn the POP approach, the
problem is viewed as a sequence ofproblem is viewed as a sequence of
things to be done such as reading,things to be done such as reading,calculating, and printing.calculating, and printing.
A number of functions areA number of functions are
written to accomplish these tasks. Thewritten to accomplish these tasks. Theprimary focus is on Functions.primary focus is on Functions.
1/1/20121/1/2012 11ATK.PrasannaATK.Prasanna kumarkumar forfor SSiSSi--AptechAptech
-
8/3/2019 Cpp Latest
2/125
22
POP Approach DiagramPOP Approach Diagram
Main Program
Function-1 Function-2 Function-3
Function-4 Function-5
Function-6 Function-7 Function-8
1/1/2012 2ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
3/125
33
In multiIn multi--function programming , manyfunction programming , many
important data items are placed asimportant data items are placed as globalglobalsoso
that they may be accessed by all thethat they may be accessed by all the
functions. Each function may have its ownfunctions. Each function may have its own
local datalocal data..
Global data Global data
Function-1
Local data
Function-2
Local data
Function-3
Local data
1/1/2012 ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
4/125
44
Drawbacks in POP ApproachDrawbacks in POP ApproachGlobalGlobal datadata movemove openly around the systemopenly around the system
from function to function.from function to function.In a large program it is very difficult to identifyIn a large program it is very difficult to identify
what data is used by which function.what data is used by which function.
In case we need to revise an external dataIn case we need to revise an external datastructure, we also need to revise all functionsstructure, we also need to revise all functionsthat access the data.that access the data.
NoteNote::POP approach does not model real worldPOP approach does not model real worldproblems very well, because functions areproblems very well, because functions are
actionaction--oriented and do not really correspond tooriented and do not really correspond tothe elements of the problem.the elements of the problem.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
5/125
55
ObjectObject--Oriented ProgrammingOriented Programming
Object Oriented Programming treatsObject Oriented Programming treats
data as a critical element in the programdata as a critical element in the program
development and does not allow it to flowdevelopment and does not allow it to flowfreely around the system. It ties data morefreely around the system. It ties data more
closely to the functions that operate on it,closely to the functions that operate on it,
and protects it from accidental modificationand protects it from accidental modificationfrom outside functions.from outside functions.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
6/125
66
OOPOOP allows decomposition of aallows decomposition of a
problem into a number of entities calledproblem into a number of entities calledobjects and then builds data and functionsobjects and then builds data and functions
around these objects.around these objects.
The data of an object can beThe data of an object can be
accessed only by the functions associatedaccessed only by the functions associated
with that objects. The functions of onewith that objects. The functions of oneobject can access the functions of otherobject can access the functions of other
objects.objects.1/1/2012 ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
7/125
77
OOPs Approach DiagramOOPs Approach Diagram
Data
Functions
Data
Functions
Object A Object B
Functions
Data
Object C
Communication
1/1/2012 ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
8/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 8
HistoryHistory
C++ is an objectC++ is an object--oriented extension ofCoriented extension ofC
C was designed by Dennis Ritchie at Bell LabsC was designed by Dennis Ritchie at Bell Labs
used to write Unix, based on BCPLused to write Unix, based on BCPL
C++ designed byC++ designed by BjarneBjarne StroustrupStroustrup at Bell Labsat Bell Labs
Called C with classes in early 1980sCalled C with classes in early 1980s
Popularity increased in late 1980s and earlyPopularity increased in late 1980s and early
1990s.1990s.
-
8/3/2019 Cpp Latest
9/125
Basic concepts of OOPBasic concepts of OOP
1.Object:Objects are primary run-time entities in an
object oriented programming. An object is
a specimen of a class. Objects occupyspace in memory. Every object has its own
properties or features. The action of the
object depends upon the member functiondefined within its class.
1/1/2012 9ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
10/125
Commonly available objectsCommonly available objects
1/1/2012 10ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
11/125
2.Classes:
A class is grouping of objects having identical
properties, common behavior, and shared
relationship. The entire group of data and code
of an object can be built as a user-defined data
type using class. Objects are nothing but
variables of type class. Once a class has been
declared, the programmer can create a number
of objects associated with that class.
1/1/2012 11ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
12/125
YClass : Bus
Properties: company, model,
color, capacity
Actions: speed(), average()
Class : computerProperties: brand, price,
hard disk, RAM sizeActions: processing speed(),display()
1/1/2012 12ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
13/125
1313
Encapsulation and Data Hiding:Encapsulation and Data Hiding:
The wrapping up of data and functions into aThe wrapping up of data and functions into asingle unit (called class) is known assingle unit (called class) is known as
encapsulation.encapsulation.
The data is not accessible to the outside world,The data is not accessible to the outside world,and only those functions which are wrappedand only those functions which are wrapped
in the class can access it. These functionsin the class can access it. These functions
provide the interface between the objectsprovide the interface between the objectsdata and the program.data and the program.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
14/125
3.Method:
An operation required for an object when coded
in a class is called method. The operations are
to be defined in a class. All objects in a class
perform certain common actions or operations.
A class contains private data members and
public methods or member functions. Generally
the data members are declared private andmember functions are declared public.
1/1/2012 14ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
15/125
4. Data Abstraction
Abstraction refers to the act of representing essential
features without including the background details.
Class uses the concept of abstraction and is defined as
a list of abstract attributes such as size, cost, height
and a few functions to operate on these properties.
Since the classes use the concept of data abstraction,
they are known as Abstract Data Types (ADT).
1/1/2012 15ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
16/125
5. Encapsulation:
The packing of data and functions into a single
component is called encapsulation. Data hiding
can be accomplished with encapsulation.
In c++, the data is not accessible by outside
functions. Only those functions that are able to
access the data are defined within the class.
1/1/2012 16ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
17/125
6.Inheritance:
Inheritance is the method by which objects of
one class get the properties of objects of
another. In object oriented programming,
inheritance provides the thought of reusability.
The programmer can add new properties to the
existing class without changing it.
1/1/2012 17ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
18/125
7.Polymorphism:
Polymorphism allows the same function toact differently in different classes.
Line
Display()
Dotted objects
Display()
stars
Display()
Asterisk
Display()
1/1/2012 18ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
19/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 19
7. Dynamicbinding:
Binding refers to the linking of a procedure call to the
code to be executed in response to the call. Dynamic
binding means that the code associated with a given
procedure call is not know until the time of the call at
run time.
Dynamic is associated with polymorphism and
inheritance.
-
8/3/2019 Cpp Latest
20/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 20
C++Program features:
Comm
ents:
C++ uses a new comment symbol //.
Comments start with a double slash symbol and terminate
at the end of the line.The double slash comment is basically a single line
comment.
The C comments are more suitable for multiline comments.
-
8/3/2019 Cpp Latest
21/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 21
Outputoperator:
The identifier cout is a predefined object thatrepresents the standard output stream in C++.
The operator
-
8/3/2019 Cpp Latest
22/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 221/1/2012 ATK.Prasanna kumar for SSi-Aptech 22
Inputoperator:
The identifier cin is a predefined object thatrepresents the standard input stream in C++.
The operator >> is called an Extraction operator or
put get from operator.
Keyboard
cin 25>>
-
8/3/2019 Cpp Latest
23/125
C++ Data Types
DerivedStructure
Union
enumerationclass
Built-in
User defined
Array
FunctionPointer
reference
Integral type void Floating type
char int float double
-
8/3/2019 Cpp Latest
24/125
Streamsin C++:
C++ provides a new way to perform the input and
output operations called iostream method.
The standard header file iostream.h contains a set of
small and specific general purpose functions for
handling input and output data.
The standard input and output operations in C++ are
normally performed by using the I/O stream as cin for
input and cout for output.
1/1/2012 24ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
25/125
cout:
Syntax:
coutvarn;
1/1/2012 25ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
26/125
Frequently used unformatted input andoutput functions:
cin
get()
getline()
read()
cout
put()
write()
1/1/2012 26ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
27/125
get() and put() functions:
The single character input and output
operations in c++ can be done with the help of
these functions.
The get() is used to read a character and theput() is used to display the character on the
screen.
The syntax is:
cin.get(ch) cout.put(ch)1/1/2012 27ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
28/125
getline(), read() and write():
The getline() and write() functions are useful in
string input and output. The getline() reads the
string including white spaces.
The object cin calls the function as:
cin.getline(variable, size);
1/1/2012 28ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
29/125
read():
It also reads the text through the keyboard.
Syn: cin.read(variable,size);
When we use read statement it is necessary to
enter character equal to the number of size of
specified. The getline() statement terminates
the accepting data when enter is pressed where
as the read() continues to read characters till
the no. of characters entered are equal to the
size specified.1/1/2012 29ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
30/125
write():
The write() function is used to display the string on
the screen. Its format is the same as getline() but the
function is exactly opposite.
Syn: cout.write(variable, size);
The cout.write() statement displays only specified
number of characters given in the second argument,
though actual string may be more in length.
1/1/2012 30ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
31/125
Manipulator functions:
These are special stream functions that change
certain characteristics of the input and output.
The main advantage of these is that they
facilitate the formatting of input and outputstreams.
To carry out the operations of these in a user
program, the header file input and output
manipulator must be included.
1/1/2012 31ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
32/125
Predefined manipulators:
endl
hex, dec, oct
setbase
setw
setfill
setprecision
ws1/1/2012 32ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
33/125
1.The endl is an output manipulator togenerate a carriage return.
2. The setbase() manipulator is used to
convert the base of one numeric valueinto another base. Following are thecommon base converters.
dec (base 10) hex (base 16)oct (base 8)
1/1/2012 33ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
34/125
3. The setw() stands for the set width. Itis used to specify the minimum no. of
character positions on the output fielda variable will consume.
4. The setfill() manipulator function isused to specify a different character tofill the unused field width of the value.
5. The setprecision() is used to controlthe number of digits of an ouputstream display of a floating point value.
1/1/2012 34ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
35/125
Flags:
Format Flag
Left justification ios::left
Right justification ios::right
Fixed point notation ios::fixed
Decimal base ios::dec
Octal base ios::oct
Hexadecimal base ios::hex1/1/2012 35ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
36/125
showpoint:
The showpoint flat is used to show the decimalpoint for all floating point values. By default, thenumber of decimal position is six.
Syntax: cout.setf(ios::showpoint);Precision:
The precision member function is used to display
the floating point value as defined by the user.
Syntax: cout.precision(int n);
1/1/2012 36ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
37/125
scientific:
When scientific is set, floating point values areinserted using scientific notation. There is onlyone digit before the decimal point followed by thespecific number of precision digits which in turn
is followed by an e(exponent value).
Syntax: cout.setf(ios::scientific, ios::floatfield);
1/1/2012 37ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
38/125
fixed:
When fixed is set, the value is inserted usingdecimal notation with the specified number ofprecision digits following the decimal point.
Syntax: cout.setf(ios::fixed, ios::floatfield);
1/1/2012 38ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
39/125
Left:
If left is set, the inserted data will be flush left ina field of characters width wide. The extra space,if any, will be filled by the fill character.
Syntax: cout.setf(ios::left, ios::adjustfield);
Right:
Cout.setf(ios::right, ios::adjustfield);
1/1/2012 39ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
40/125
Some important keywords in c++:
catch class delete
friend inline new
operator private protected
public template this
throw try virtual
1/1/2012 40ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
41/125
Dynamic initialization:
The declaration and initialization of variable in a
single statement at any place in the program iscalled dynamic initialization.
In C, initialization of variables can be done at any
place but the variable must be declared at thebeginning of the program.
1/1/2012 41ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
42/125
Operators in C++:
Operator Description
> extraction operator
:: scope access (or resolution)operator
delete memory release operatornew memory allocation operator
& referencing operator1/1/2012 42ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
43/125
Referencing operator(&):
The referencing operator is used to define
referencing variable. A reference variable analternative name for previously defined variable.
Syn: data_type ref_var_name = var_name
Ex: int a = 10;
int &b = a;
If we modify the value of a, it results in changein reference variable too.
Note: Array of references is not allowed.1/1/2012 43ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
44/125
Scope access operator:
The scope access operator (::) allows aprogrammer to access a global name evenif it is hidden by a local re-declaration ofthat name.
1/1/2012 44ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
45/125
Memory management operators:
In C, we have had the functions malloc(),calloc() and realloc() to allocate memorydynamically at runtime in the program. Thefree() function is used to release the
resources allocated by these functions. C++also allows us to use these.
In addition, C++ provides us with two newoperators new and delete. The newoperator creates an object and delete
destroys it.1/1/2012 45ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
46/125
The advantages of new operator overmalloc():
1.The new operator itself calculates the size ofthe object with the use of sizeof operator.
2.It returns the pointer type. The programmers
need not take care of type casting.
3.The new operator allocates memory andinitializes the object at once.
4.The new and delete operators are very easy insyntax. They can be overloaded.
1/1/2012 46ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
47/125
The new operator:
pointer memory variable = new data type[size];
Ex: pv = new int;
pv is a pointer variable of int type.
int *pv = new int(50);
Here, 50 is assigned to pointer variable pv.
*p = new int[3];
Here, memory for 3 integers (6 bytes) areassigned to pointer variable p.
1/1/2012 47ATK.Prasanna kumar for SSi-Aptech
h d l
-
8/3/2019 Cpp Latest
48/125
The delete operator:
Syntax:
delete
delete[element size]
Ex:
delete p;
delete[5]p or delete[]p;
1/1/2012 48ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
49/125
Functions with Default arguments:
1/1/2012 49ATK.Prasanna kumar for SSi-Aptech
C++ allows us to call a function without specifying all
its arguments. In such cases, the function assigns a
default value to the parameter which doesnt have a
matching argument in the function call. Default values
are specified when the function is declared. Thecompiler looks at the prototype to see how many
arguments a function uses and alerts the program for
possible default values.
D l ti f l
-
8/3/2019 Cpp Latest
50/125
Declaration of a class:
A class definition is a process consisting the
following steps:
1.Definition of a class.
2.The internal representation of data structuresand storage.
3.The internal implementation of the interface.
4.The external operations for accessing andmanipulating the instance (object) of the class.
1/1/2012 50ATK.Prasanna kumar for SSi-Aptech
l d bjl d bj
-
8/3/2019 Cpp Latest
51/125
Class and ObjectsClass and Objects
A class is used to pack data and functionsA class is used to pack data and functions
together. The class has a mechanism totogether. The class has a mechanism toprevent direct access to its members,prevent direct access to its members,which is the central idea of oop.which is the central idea of oop.
Syntax:Syntax:
{{
private:private:
public: public:
};};1/1/2012 51ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
52/125
Declaration of objects:
A class declaration builds the structure ofobject. The member variables and functions
are combined in the class. The declarationof object is same as declaration of variablesdata types. Defining objects of class type is
known as class instantiation.
1/1/2012 52ATK.Prasanna kumar for SSi-Aptech
A bj t i b t t it h i f ll i
-
8/3/2019 Cpp Latest
53/125
An object is an abstract unit having followingproperties:
1.It is an individual.
2.It points to a thing, either physical or logicalthat is identifiable by the user.
3.It holds data as well as operation method thathandles data.
4.Its scope is limited to the block in which it isdefined.
1/1/2012 53ATK.Prasanna kumar for SSi-Aptech
P i t b f ti
-
8/3/2019 Cpp Latest
54/125
Private member function:
To execute private member function, itmust be invoked by public member functionof the same class. A member function of aclass can invoke any other member function
of its own class. This method of invokingfunction is known as nesting of memberfunctions.
1/1/2012 54ATK.Prasanna kumar for SSi-Aptech
M b f ti t id th l
-
8/3/2019 Cpp Latest
55/125
Member function outside the class:
To define a function outside the class ,
1.The prototype of function must bedeclared inside the class.
2.The function name must be preceded byclass name and its return type separatedby scope access operator.
1/1/2012 55ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
56/125
Inline function:
In C++, you can create short functions that are
not actually called; rather, their code isexpanded in line at the point of each
invocation. This process is similar to using a
function-like macro. To cause a function to beexpanded in line rather than called, precede
its definition with the inline keyword.
Syntax: inline {
function body
}1/1/2012 56ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
57/125
Since classes typically require several frequently
executed interface functions, the efficiency ofthese functions are of critical concern. Each
time a function is called, a significant amount of
overhead is generated by the calling and returnmechanism. Typically, arguments are pushed
onto the stack and various registers are saved
when a function is called, and then restoredwhen the function returns. These instructions
take time.1/1/2012 57ATK.Prasanna kumar for SSi-Aptech
-
8/3/2019 Cpp Latest
58/125
However, when a function is expanded in
line, none of those operations occur.
Although expanding function calls in line can
produce faster run times, it can also resultin larger code size because of duplicated
code. For this reason, it is best to inline
only very small functions.
1/1/2012 58ATK.Prasanna kumar for SSi-Aptech
Ouside member function inline:
-
8/3/2019 Cpp Latest
59/125
Ouside member function inline:
An inline member function is similar to macros.
Call to inline function in the program, puts thefunction code in the caller program. This is knows as
inline expansion. Inline functions are also called open
subroutines because their code is replaced at the
place of function call in the caller function. The
normal functions are called closed subroutines
because when such functions are called, the control
passes to the function.
By default all member functions defined inside
the class are inline functions.1/1/2012 59ATK.Prasanna kumar for SSi-Aptech
The member function defined outside the class
-
8/3/2019 Cpp Latest
60/125
The member function defined outside the class
can be made inline by prefixing the keyword
inline to function declarator.
Inline return_type class_name :: function
name(argument list)
1/1/2012 60ATK.Prasanna kumar for SSi-Aptech
Memory allocation for object :
-
8/3/2019 Cpp Latest
61/125
Memory allocation for object :
Common for all objects
Member function 1 Member function 2
Member variable1
Member variable2
Member variable1
Member variable2
Memory created when functions defined
Memory created when objects defined
Object 2Object 2Object 1Object 1
1/1/2012 61ATK.Prasanna kumar for SSi-Aptech
The memory space for objects is allocated only
-
8/3/2019 Cpp Latest
62/125
The memory space for objects is allocated only
when they are declared and not when the class is
specified. Actually, the member functions arecreated and placed in the memory space only
when they are defined as a part of a class
specification. Since all the objects belonging to
that class use the same member functions, no
separate space is allocated for member functions.
Only space for member variables is allocated
separately for each object. This is essentialbecause the member variables will hold different
data values for different objects.1/1/2012 62ATK.Prasanna kumar for SSi-Aptech
Static DataMembers
-
8/3/2019 Cpp Latest
63/125
Static DataMembers
When we declare a member variable static, we are
telling the compiler that only one copy of thatvariable will exist and that all objects of the class
will share that variable. Unlike regular data
members, individual copies of a static member
variable are not made for each object. No matter
how many objects of a class are created, only one
copyof a static data member exists. Thus, all
objects of that class use that same variable. Allstatic variables are initialized to zero before the
first object is created.1/1/2012 63ATK.Prasanna kumar for SSi-Aptech
Obj A Obj B
-
8/3/2019 Cpp Latest
64/125
1/1/2012 64
ATK.Prasanna kumar for SSi-Aptech
var1
var2
varn
Object A
var1
var2
varn
Object B
var1var2
varn
Object C
Static variable
N t
-
8/3/2019 Cpp Latest
65/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 65
Note:
The type and scope of each static member
variable must be defined outside the classdefinition.
This is necessary because the static datamembers are stored separately rather than as
part of an object. They are also known as class
variables.
t ti b f ti
-
8/3/2019 Cpp Latest
66/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 66
We can also declare member functions as static
such a functions are called as static memberfunctions.
Characteristics:A static function can have access to only otherstatic members (functions or variables) declaredin same class.
A static member function can be called usingthe class name (instead of its objects) .
static member functions
-
8/3/2019 Cpp Latest
67/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 67
Staticobject:
In C, it is common to declare variable static that gets
initialized to zero. The object is a composition of oneor more variables. The keyword static can be used to
initialize all class data member variables to zero.
Declaring object itself as static can do that. Thus, allits associated members get initialized to zero.
Friend Functions
-
8/3/2019 Cpp Latest
68/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 68
Friend Functions
The private members cannot be accessed from
outside the class. That is, a non-member
function cannot have an access to the private
data of a class.
When a private data member is changed topublic category, it violates the whole concept of
data hiding and data encapsulation. To solve
this problem, a friend function can be declaredto have access to these data members.
Friend is a special mechanism for letting non-
-
8/3/2019 Cpp Latest
69/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 69
Friend is a special mechanism for letting non-
member functions access private data. A friend
function may be either declared or definedwithin the scope of a class definition. The
keyword friend inform the compiler that it is not
a member function of the class.Syntax:
Friend return_type fun_name(parameters);
Granting friendship to another class:
-
8/3/2019 Cpp Latest
70/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 70
Granting friendship to another class:
A class can have friendship with another class.
For example, let there be two classes, first andsecond. If the class first grants friendship with
the other class second, then the private data
members of the class first are permitted to beaccessed by the public member functions of the
class second. But on the other hand, the public
member functions of the class first cannotaccess the private members of the class second.
The general syntax:
-
8/3/2019 Cpp Latest
71/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 71
The general syntax:Class second;//forward declarationClass first
{private:Public:friend ret_type fun_name(class first, class second);
};Class second{private:
public:friend ret_type fun_name(class first, class second);
};
Two classes having the same friend:
-
8/3/2019 Cpp Latest
72/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 72
Twoclasseshaving thesame friend:
A non-member function may have friendship
with one or more classes. When a function hasdeclared to have friendship with more than
one class, the friend classes should have
forward declaration. It implies that it needs toaccess the private members of both classes.
-
8/3/2019 Cpp Latest
73/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 73
A friend function can be called by
reference. In this case, local copies of the
objects are not made. Instead, a pointer to
the address of the object is passed and the
called function directly works on the actualobject used in the call.
Constructors and destructors
-
8/3/2019 Cpp Latest
74/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 74
Constructors and destructorsA constructor is a special member function
whose task is to initialize the objects of itsclass. The constructor is invoked whenever an
object of its associated class is created. Its
name is same as the class name.A destructor is used to destroy the objects that
have been created by a constructor. Its name
is the same as class name but preceded by atilde(~) operator.
Characteristics of constructors:
-
8/3/2019 Cpp Latest
75/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 75
Characteristicsofconstructors:
1. Constructor has the same name as that of the
class it belongs.
2. Constructor is executed when an object is
declared
3. Constructors have neither return value nor void.
4. The main function of constructor is to initialize
objects and allocate appropriate memory to
objects.
5. Constructors without arguments are calleddefault arguments.
Constructors with arguments:
-
8/3/2019 Cpp Latest
76/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 76
Constructors with arguments:
The constructors with arguments are called
parameterized constructors. For theseconstructors, it is necessary to pass values to
the constructor when object is created.
Copy constructor
-
8/3/2019 Cpp Latest
77/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 77
Copy constructorThe constructor can accept arguments of anydata type including user-defined data types andan object of its own class.
statement(a) statement(b)class num class num
{ {private: private:
.. public: public:num(num); num(num &);} }
In statement (a) an argument of the constructor is
-
8/3/2019 Cpp Latest
78/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 78
( ) gsame as that of its class. Hence, this declaration iswrong. It is possible to pass reference of object of the
constructor. Such declaration is known as copyconstructor. The statement (b) is valid and can be usedto copy constructor.
when we pass an object by value into a function, a
temporary copy of that object is created. All copyconstructor require one argument, with reference to anobject of that class. Using copy constructors, it ispossible for the programmers to declare and initialize
one object using reference of another object. Thus,whenever a constructor is called a copy of an object iscreated.
Function overloading:
-
8/3/2019 Cpp Latest
79/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 79
Function overloading:
In C++, it is possible to use the same function
for a number of times for different intentions.Defining multiple functions with same name is
called function overloading or function
polymorphism.The overloaded function must be different in its
argument list and with different data types.
Principles of function overloading:
-
8/3/2019 Cpp Latest
80/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 80
Principlesof function overloading:
1. If two functions have the similar type and number
of arguments (data type), the function cannot beoverloaded.
sum(int, int, int);
sum(int, int);
sum(int, int, int);
sum(float, float, float);
These two can be overloaded.
2 The compiler attempts to find an accurate
-
8/3/2019 Cpp Latest
81/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 81
2. The compiler attempts to find an accurate
function definition that matches in types and
number of arguments and invokes that function.The arguments passed are checked with all
declared functions. If matching function is found
then that function gets executed.3. If there is no accurate match found, compiler
makes the implicit conversion of actual argument.
For example, char is converted to int and float is
converted to double.
Overloading constructors:
-
8/3/2019 Cpp Latest
82/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 82
Overloading constructors:
Like functions, it is also possible to overload
constructors. A class can contain more than oneconstructor. This is called constructor
overloading. All constructors are defined with
the same name as the class. All the constructorscontain different number of arguments.
Depending upon number of arguments, the
compiler executes appropriate constructor.
Constructorswith default arguments:
-
8/3/2019 Cpp Latest
83/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 83
Constructorswith defaultarguments:
Like functions, it is also possible to declare
constructors with default arguments.
Destructors:
-
8/3/2019 Cpp Latest
84/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 84
Destructor is a special member function like
constructor. Destructors destroy the class objects
created by constructors. The destructors have the
same name as their class, preceded by tilde (~).
For local and non-static objects, the destructor is
executed when the object goes out of the scope. Incase the program is terminated by using return
statements, the destructor is executed for every
object existing at that time. It is not possible to
define more than one destructor. The destructor is
only one way to destroy the object.
Operatoroverloading:
-
8/3/2019 Cpp Latest
85/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 85
p g
C++ has the ability to treat user-defined data type like
the one they were built-in type. User-defined data
types created from class or struct are nothing but
combination of one or more variables of basic data
types. The compiler knows how to perform various
operations using operators for built-in types. Thecompiler would throw an error if we want to perform
an operation between two objects using operators.
Therefore, for the objects, the operation routine
must be defined by the programmer.
The key word operator defines a new action or
-
8/3/2019 Cpp Latest
86/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 86
The key word operator defines a new action or
operation to the operator.
Syntax:
Return_type operatorop_symbol(parameters)
{
statement 1;
statement 2;}
The keyword operator, followed by an operator
symbol, defines a new (overloaded) action of thegiven operator.
Rules for overloading operators:
-
8/3/2019 Cpp Latest
87/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 87
Rules for overloading operators:
1. Overloading of an operator cannot change the
basic idea of an operator. When an operator isoverloaded, its properties like syntax, precedence
and associatively remain constant.
Ex: a+ = b; is a=a+b;
2. Overloading of an operator must never change itsnatural meaning. An overloaded operator + can be
used for subtraction of two objects, but this type
of code decreases the utility of the program.
When ++ and operators are overloaded, the system
-
8/3/2019 Cpp Latest
88/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 88
cant determine whether the operators are
overloaded for prefix or postfix operations. Hence,
the operator must be overloaded in such a way that it
will for both prefix and postfix operations. To make a
distinction between prefix and postfix notation, a new
syntax is used to indicate postfix operator overloadingfunction. The syntaxes are:
operator ++ (int) //postfix notation
operator ++() //prefix notation
Inheritance:
-
8/3/2019 Cpp Latest
89/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 89
Using inheritance, we can create a general class that
defines traits common to a set of related items. This
class may then be inherited by other, more specific
classes, each adding only those things that are unique
to the inheriting class. In keeping with standard C++
terminology, a class that is inherited is referred to as abase class. The class that does the inheriting is called
the derived class. Further, a derived class can be used
as a base class for another derived class. In this way,
multiple inheritance is achieved.
Class inheritance uses this general form
-
8/3/2019 Cpp Latest
90/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 90
Class inheritance uses this general form:
class derived-class-name: access base-class-name
{// body of class
};
The access status of the base-class members inside
the derived class is determined by access.
Private inheritance:
-
8/3/2019 Cpp Latest
91/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 91
Privateinheritance:
When a base class is privately inherited by a derivedclass, public and protected members of the base
class become the private members of the derived
class. Therefore the public members of the base class
can only be accessed by the member functions of the
derived class.
Publicinheritance:
-
8/3/2019 Cpp Latest
92/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 92
When a base class is publicly inherited by a derived
class, public members of the base class become the
public members of the derived class and protected
members of the base class become the protected
members of the derived class. Therefore publicmembers of the base class can accessible to the
objects of the derived class.
Protected inheritance:
-
8/3/2019 Cpp Latest
93/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 93
When the base class is protectedly inherited by a
derived class, public and protected members of the
base class become the protected members of the
derived class. Therefore public members of the
base class can be accessed by the member functionsof the derived class.
Inheritanceand protected Members:
-
8/3/2019 Cpp Latest
94/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 94
A private member of a base class is not
accessible by other parts of our program, including
any derived class. However, protected members
behave differently. If the base class is inherited as
public, then the base class' protected members
become protected members of the derived class andare, therefore, accessible by the derived class. By
using protected, you can create class members that
are private to their class but that can still be inherited
and accessed by a derived class.
Note:
-
8/3/2019 Cpp Latest
95/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 95
Note:
When a derived class is used as a base class for
another derived class, any protected member of theinitial base class that is inherited (as public) by the
first derived class may also be inherited as protected
again by a second derived class.
Types ofinheritance:
-
8/3/2019 Cpp Latest
96/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 96
1. Single inheritance: If a class inherits from one base
class is called single inheritance.
2. Multiple inheritance: If a class inherits from more
than one base class is called multiple inheritance.
3. Multilevel inheritance: If a class derived from aderived class is class multilevel inheritance.
4. Hierarchical inheritance: The mechanism of
deriving more than one derived class is called
hierarchical inheritance.
-
8/3/2019 Cpp Latest
97/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 97
Constructorsin
inheritance
Case-1:
-
8/3/2019 Cpp Latest
98/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 98
When base class has default constructor(withoutarguments), the derived class need not have a
constructor function.case-2:However, if any base class contains a constructor
with one or more arguments, then it ismandatory for the derived class to have aconstructor with arguments and pass thearguments to the base class constructors.
while applying inheritance we usually create
-
8/3/2019 Cpp Latest
99/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 99
objects using the derived class. Thus, it makes sense
for the derived class to pass arguments to the base
class constructor.
The constructor of the derived class receives the
entire list of values as its arguments and passes
them on to the base class constructors in the order inwhich they are declared in the base class.
When both the derived and base classes contain
constructors, the base class constructor is executed
first and then the derived class constructor.
C++ supports a special constructor member function
-
8/3/2019 Cpp Latest
100/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 100
such a situations.
Syntax:
Derived-constructor(args list) :
base-constructor(arg1),
base-constructor(arg2),...
{// body of the derived
// class constructor
. . .
. . .
}
Templates:
l h h bl d f
-
8/3/2019 Cpp Latest
101/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 101
Template is a concept which enables us to define
generic classes and functions and thus provides
support for generic programming.
Genericprogramming:
It is an approach where generic types are used as
parameters in algorithms so that they for a variety ofsuitable data types and data structures.
A template can be used to create a family of classes or
f i
-
8/3/2019 Cpp Latest
102/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 102
functions.
For example, a class template for an array class would
enable us to create arrays of various data types.
Similarly, we can define a template for a function, say
sum(), that would help us create various versions of
sum() for adding int, float and double data types.A template can be considered as a kind of macro.
When an object of a specified type is defined for
actual use, the template definition for that class is
substituted with the required data type. Template can
be called parameterized classes or functions.
-
8/3/2019 Cpp Latest
103/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 103
Definition of class template:
Template class
Class class_name
{
//data members and functions
}
Normal function template:
-
8/3/2019 Cpp Latest
104/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 104
Declaration:
template class
function_name()
{//code
}
Template with multiple parameters:
-
8/3/2019 Cpp Latest
105/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 105
Template with multiple parameters:
TemplateClass class_name{
class dec & def}
Function templates with more arguments:
-
8/3/2019 Cpp Latest
106/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 106
Function templates with more arguments:
Templateret_type fun_name(parameters of template type)
{
statement 1;statement 2;
statement 3;
}
Exception handling
-
8/3/2019 Cpp Latest
107/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 107
Errors
logical errors syntactic errors
Logical errors occur due to poor understanding of the
problem and solution procedure.Syntactic errors occur due to poor understanding of the
language itself.
Other than these two, we come across peculiar problems
which are called exceptions. These are runtime anomalieslike division by zero, access to an array outside of its bounds,
running out of disk space etc.,
-
8/3/2019 Cpp Latest
108/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 108
Exception handling allows us to manage run-
time errors in an orderly fashion. Using exception
handling, our program can automatically invoke an
error-handling routine when an error occurs.
C++ exception handling is built upon three keywords: try,
catch and throw In the most general terms program
-
8/3/2019 Cpp Latest
109/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 109
catch, and throw. In the most general terms, program
statements that we want to monitor for exceptions are
contained in a try block. If an exception (i.e., an error) occurswithin the try block, it is thrown (using throw). The exception
is caught, using catch, and processed.
try blockDetects and throws
an exception
catch blockDetects and throws
an exception
Exception
object
The general form of try, throw and catch:
-
8/3/2019 Cpp Latest
110/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 110
try
{
...throwexception
.
}
catch (type arg)
{
// catch block
}
When the tryblock throws
an exception, the programcontrol leaves the try block
and enters the catch
statement of the catch
block. Exceptions are
objects used to transmit
information about a
problem.
th i t
Function invoked bytryblockthrowing exception
-
8/3/2019 Cpp Latest
111/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 111
try blockInvokes a function that
contains exception
catch blockCatches and handles
the exception
ThrowException
throw pointFunction that causes
an exceptionInvoke
function
Multiplecatchstatements:
We can also define multiple catch blocks in try blocks
-
8/3/2019 Cpp Latest
112/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 112
We can also define multiple catch blocks, in try blocks.
Such program also contain multiple throw statements
based on certain conditions.try
{ //try block }
catch(type1 arg){ //catch block1 }
catch(type2 arg)
{ //catch block 2}
:::::::::::::::::::::
catch(typeN arg)
{//catch block N}
As soon as the an exception is thrown, the
-
8/3/2019 Cpp Latest
113/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 113
p ,
compiler searches for appropriate match by matching
catch() block. The matching catch() block is executedand control passes to the successive statement after
the last catch() block. In case no match is found, the
program terminates.
In multiple catch() statement, if objects of many
catch statements are similar to type of an exception,
in such a situation the first catch () block that matches
is executed.
Catching all Exceptions:
In some situations we may not be able to anticipate
-
8/3/2019 Cpp Latest
114/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 114
In some situations, we may not be able to anticipate
all possible types of exceptions and therefore may not
be able to design independent catch handlers to catchthem. In such situations, we can force a catch
statement to catch all exceptions instead of a certain
type alone. This can be achieved by defining the catchstatement using ellipses.
catch()
{ //all exceptions }
Note: catch() should always be placed last in the list
of handlers.
Thispointer:
If p is an object of class sample and get() is a member
-
8/3/2019 Cpp Latest
115/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 115
If p is an object of class sample and get() is a member
function of sample, the statement p.get() us used to
call that function. The statement p.get() operates onp. in the same way if ptr is a pointer to p object, the
function called ptr -> get() operates on *ptr.
C++ compiler provides get() with a pointer to p calledthis. The pointer this is transferred as an unseen
parameter in all calls to non-static member functions.
The key word this is a local variable that is always
present in the body of any non-static member
function.
Operators newand new[]
In order to request dynamic memory we use the operator
-
8/3/2019 Cpp Latest
116/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 116
In order to request dynamic memory we use the operator
new. new is followed by a data type specifier.
If a sequence of more than one element is required- thenumber of these within brackets [].
It returns a pointer to the beginning of the new block of
memory allocated. Its form is:
pointer = new type
pointer = new type [no_of_elements]
The first expression is used to allocate memory to contain
one single element of type type. The second one is usedto assign a block (an array) of elements.
Operator deleteand delete[]
Since the necessity of dynamic memory is usually
-
8/3/2019 Cpp Latest
117/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 117
Since the necessity of dynamic memory is usually
limited to specific moments within a program, once it
is no longer needed it should be freed so that thememory becomes available again for other requests
of dynamic memory. This is the purpose of the
operator delete, whose format is:delete pointer;
delete [] pointer;
The first expression should be used to delete memory
allocated for a single element, and the second one for
memory allocated for arrays of elements.
Advantagesof newovermalloc():
1. It automatically computes the size of the data object. We
-
8/3/2019 Cpp Latest
118/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 118
1. It automatically computes the size of the data object. We
need not use the operator sizeof.
2. It automatically returns the correct pointer type, so thatthere is not need to use a type cast.
3. It is possible to initialize the object while creating the
memory space.
4. Like any other operator, new and delete can beoverloaded.
Dynamicconstructors:
-
8/3/2019 Cpp Latest
119/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 119
The constructors can also be used to allocate
memory while creating objects. This will enable thesystem to allocate the right amount of memory for
each object when the objects are not of the same
size, thus resulting in the saving of memory.Allocation of memory to objects at the time of their
construction is called dynamic construction of objects.
Virtual functions:
Virtual functions of base classes must be
-
8/3/2019 Cpp Latest
120/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 120
Virtual functions of base classes must be
redefined in the derived classes. The programmer can
define a virtual function in a base class and can usethe same function name in any derived class, even if
the number and type of arguments are matching. The
matching function overrides the base class function ofthe same name. virtual functions can only be member
functions.
Rules forVirtual functions:
1. The virtual function should not be static and must be a
-
8/3/2019 Cpp Latest
121/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 121
1. The virtual function should not be static and must be a
member class.
2. A virtual function may be declared as friend foranother class.
3. Constructors can not be declared as virtual, but
destructors can be.
4. The virtual function must be defined in public section
of the class.
5. The prototype of virtual function in base and derived
classes should be exactly the same. In case ofmismatch, the compiler neglects the virtual function
mechanism and treats them as overloaded functions.
Purevirtual functions:
A pure virtual function is a function declared in a base
-
8/3/2019 Cpp Latest
122/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 122
A pure virtual function is a function declared in a base
class that has no definition relative to the base class. In
such cases, the compiler requires each derived classeither define the function or redeclare it as a pure virtual
function. A class containing pure virtual functions cannot
be used to declare any objects of its own. Such classes are
called abstract base classes. The main objective of an
abstract base class is to provide some traits to the derived
classes and to create a base pointer required for
achieving run time polymorphism.
Ex:
Virtual void display() = 0;
-
8/3/2019 Cpp Latest
123/125
An essential requirement to take advantage ofpolymorphism in C++ is that there should be a
-
8/3/2019 Cpp Latest
124/125
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 124
polymorphism in C++ is that there should be away by which it is possible to refer to objects of
derived classes using a pointer to a single type.This is possible by using a pointer to the basetype, which can also point to derived class
objects.Whenever a derived class redefines a function inthe base class, the function needs to be declared
virtual by prefixing the keyword virtual to the
normal function declaration in the base class.This should be done if the programmer wishes totake advantage of run-time polymorphism.
-
8/3/2019 Cpp Latest
125/125