Upload
crystal-smith
View
221
Download
0
Embed Size (px)
Citation preview
8/16/2019 Introduction to C++.docx
1/107
Introduction to C++
C++ - an extension to C language Stroustrup at bell labs.
C++ is an intermediate level language, comprises both high and low level
language features.
C++ is a multiparadigm, compiled general-purpose language.
C++ is an Object Oriented Programming language - not purely Object
Oriented.
Friend and Virtual, violate some of the very important OO! features,
Benefits of C++ over C Language
"ollowing features of C++ ma#es it a stronger language than C,
$. %ll the OO! features in C++ li#e %bstraction, &ncapsulation,
Inheritance etc ma#es it more worthy and useful for programmers.
'. C++ supports and allows user defined operators (i.e Operator
Overloading) and function overloading is also supported in it.
*. &xception andling is there in C++.
. he Concept of irtual functions and also Constructors and
/estructors for Objects.
0. Inline "unctions in C++ instead of 1acros in C language.
8/16/2019 Introduction to C++.docx
2/107
2. ariables can be declared anywhere in the program in C++, but must
be declared before they are used.
C++ and Object Oriented Programming
Object Oriented programming is a programming style that is associated
with the concept of Class, Objects and various other concepts revovling
around these two, li#e Inheritance, olymorphism, %bstraction,
&ncapsulation etc.
OOPS Concept Definitions
features of Object Oriented rogramming in C++(technically).
$. Objects
'. Classes
*. %bstraction
8/16/2019 Introduction to C++.docx
3/107
. &ncapsulation
0. Inheritance
2. Overloading
3. &xception andling
Objects
Objects are the basic unit of OO. hey are instances of class, which have
data members and uses various member functions to perform tas#s.
Class
It is similar to structures in C language. Class can also be defined as user
defined data type but it also contains functions in it. !o, class is basically a
blueprint for object. It declare 4 defines what data variables the object will
have and what operations can be performed on the class5s object.
Abstraction
%bstraction refers to showing only the essential features of the application
and hiding the details. In C++, classes provide methods to the outside
world to access 4 use the data variables, but the variables are hidden from
direct access. his can be done access specifiers.
8/16/2019 Introduction to C++.docx
4/107
Encapsulation
It can also be said data binding. &ncapsulation is all about binding the data
variables and functions together in class.
Ineritance
Inheritance is a way to reuse once written code again and again. he class
which is inherited is called base calls 4 the class which inherits is called
derived class. !o when, a derived class inherits a base class, the derived
class can use all the functions which are defined in base class, hence
ma#ing code reusable.
Pol!morpism
It is a feature, which lets us create functions with same name but different
arguments, which will perform differently. hat is function with same name,
functioning in different way. Or, it also allows us to redefine a function to
provide its new definition. 6ou will learn how to do this in details soon in
coming lessons.
E"ception #andling
&xception handling is a feature of OO, to handle unresolved exceptions or
errors produced at runtime.
8/16/2019 Introduction to C++.docx
5/107
Basics of C++
S!nta" and Structure of C++ program
$irst C++ program
include
using namespace std;
int main()
{
cout
8/16/2019 Introduction to C++.docx
6/107
Example : std::cout
8/16/2019 Introduction to C++.docx
7/107
int i; data &aria%le
&oid displa'() em%er Function
{
cout
8/16/2019 Introduction to C++.docx
8/107
int add(int i,int j )
{
int sum;
sum = i+j;
cout
8/16/2019 Introduction to C++.docx
9/107
&oid displa'() em%er Function
{
cout
8/16/2019 Introduction to C++.docx
10/107
int for integral number ( ' bytes )
0oat single precision floating point ( bytes )
dou%le double precision floating point numbers ( : bytes )
Example 8
char a . ; character t'pe
int a . 1; integer t'pe
0oat a . 2,13145; 0oating point t'pe
dou%le a . 6e73; dou%le t'pe (e is !or e8ponential)
Oter Built in t!pes
%ool ;oolean ( rue or "alse )
&oid
8/16/2019 Introduction to C++.docx
11/107
"or &xample 8
enum da'(mon- tues- 9ed- thurs- !ri) d;
ere an enumeration of days is defined with variable d. mon will hold value
>, tue will have $ and so on.
8/16/2019 Introduction to C++.docx
12/107
• !i?e hierarchy 8 short int < int < long int
• !i?e hierarchy for floating point numbers is 8 0oat < dou%le < long
dou%le
• long float is not a legal type and there are no sort floating
point numbers.
• Signed types includes both positive and negative numbers and is the
default type.
• %nsigned, numbers are always without any sign, that is always
positive.
-at are .ariables
ariable are used in C++, where we need storage for any value, which will
change in program. ariable can be declared in multiple ways each with
different memory re=uirements and functioning. ariable is the name ofmemory location allocated by the compiler depending upon the datatype of
the variable.
8/16/2019 Introduction to C++.docx
13/107
Basic t!pes of .ariables
&ach variable while declaration must be given a datatype, on which the
memory assigned to the variable depends. "ollowing are the basic types of
variables,
%ool "or variable to store boolean values( rue or "alse )
char "or variables to store character types.
int for variable with integral values
0oat and dou%le are also types for variables with large and
floating point values
Declaration and Initiali/ation
8/16/2019 Introduction to C++.docx
14/107
ariable must be declared before they are used. @sually it is preferred to
declare them at the starting of the program, but in C++ they can be
declared in the middle of program too, but must be done before using them.
Example 8
int i; declared %ut not initialised
char c;
int i- *- ; ultiple declaration
Initiali?ation means assigning value to an already declared variable,
int i; declaration
i . 1=; initialiation
Initiali?ation and declaration can be done in one single step also,
int i.1=; initialiation and declaration in same step
int i.1=- *.11;
If a variable is declared and not initiali?ed by default it will hold a garbage
value. %lso, if a variable is once declared and if try to declare it again, we
will get a compile time error.
int i-*;
i.1=;
*.?=;
int *.i+*; compile time error- cannot redeclare a &aria%le in
same scope
8/16/2019 Introduction to C++.docx
15/107
Scope of .ariables
%ll the variables have their area of functioning, and out of that boundary
they don5t hold their value, this boundary is called scope of the variable. "or
most of the cases its between the curly braces, in which variable is
declared that a variable exists, not outside it.
8/16/2019 Introduction to C++.docx
16/107
{
8.1=; nitialied once
cout
8/16/2019 Introduction to C++.docx
17/107
cout
8/16/2019 Introduction to C++.docx
18/107
multiplication () etc, are all operators. Operators are used to perform
various operations on variables and constants.
!pes of operators
$. %ssignment Operator
'. 1athematical Operators
*. Delational Operators
. Bogical Operators
0. ;itwise Operators
2. !hift Operators
3. @nary Operators
:. ernary Operator
E. Comma Operator
8/16/2019 Introduction to C++.docx
19/107
Assignment Operator & 1 '
Operates 5F5 is used for assignment, it ta#es the right-hand side (called
rvalue) and copy it into the left-hand side (called lvalue). %ssignment
operator is the only operator which can be overloaded but cannot be
inherited.
,atematical Operators
here are operators used to perform basic mathematical operations.
%ddition (+) , subtraction (-) , diversion (G) multiplication () and modulus (9)
are the basic mathematical operators. 1odulus operator cannot be used
with floating-point numbers.
C++ and C also use a shorthand notation to perform an operation and
assignment at same type. Example,
int 8.1=;
8 +. 3 9ill add 3 to 1=- and hence assign 13 to ,
8 7. 4 9ill su%tract 4 !rom 1= and assign 4 to 8,
2elational Operators
hese operators establish a relationship between operands. he relational
operators are 8 less than (H) , grater thatn () , less than or e=ual to (HF),
greater than e=ual to (F), e=uivalent (FF) and not e=uivalent (JF).
8/16/2019 Introduction to C++.docx
20/107
6ou must notice that assignment operator is (F) and there is a relational
operator, for e=uivalent (FF). hese two are different from each other, the
assignment operator assigns the value to any variable, whereas e=uivalent
operator is used to compare values, li#e in if-else conditions, Example
int 8 . 1=; assignment operator
8.4; again assignment operator
i!(8 .. 4) here 9e ha&e used eDui&alent relational operator-
!or comparison
{
cout
8/16/2019 Introduction to C++.docx
21/107
here are used to change individual bits into a number. hey wor# with only
integral data types li#e char,int and long and not with floating point
values.
• ;itwise %7/ operators
• ;itwise OD operator G
• %nd bitwise LOD operator
• %nd, bitwise 7O operator I
hey can be used as shorthand notation too, . , G. , . , I. etc.
Sift Operators
!hift Operators are used to shift ;its of any variable. It is of three types,
$. Beft !hift Operator
8/16/2019 Introduction to C++.docx
22/107
8/16/2019 Introduction to C++.docx
23/107
int i . sieL! 8;
t!pedef Operator
t!pedef is a #eyword used in C language to assign alternative names to
existing types. Its mostly used with user defined data types, when names of
data types get slightly complicated. "ollowing is the general syntax for
using typedef,
typedef existing_name alias_name
Bets ta#e an example and see how typedef actually wor#s.
t'pede! unsigned long ulong;
he above statement define a term ulong for an unsigned long type. 7ow
this ulong identifier can be used to define unsigned long type variables.
ulong i- * ;
t!pedef and Pointers
typedef can be used to give an alias name to pointers also. ere we have a
case in which use of typedef is beneficial during pointer declaration.
In ointers $ binds to the right and not the left.
int$ 8- ' ;
;y this declaration statement, we are actually declaring " as a pointer of
type int, whereas ! will be declared as a plain integer.
8/16/2019 Introduction to C++.docx
24/107
t'pede! int$ IntPtr ;
IntPtr 8- '- ;
;ut if we use t!pedef li#e in above example, we can declare any number of
pointers in a single statement.
Decision ma5ing in C++
/ecision ma#ing is about deciding the order of execution of statements
based on certain conditions or repeat a group of statements until certain
specified conditions are met. C++ handles decision-ma#ing by supporting
the following statements,
• if statement
• switch statement
• conditional operator statement
• goto statement
Decision ma5ing 3it if statement
he if statement may be implemented in different forms depending on the
complexity of conditions to be tested. he different forms are,
$. !imple if statement
'. If....else statement
*. 7ested if....else statement
8/16/2019 Introduction to C++.docx
25/107
. else if statement
Simple if statement
he general form of a simple if statement is,
i!( e8pression )
{
statement7inside;
}
statement7outside;
If the expression is true, then 5statement-inside5 it will be executed,
otherwise 5statement-inside5 is s#ipped and only 5statement-outside5 is
executed.
E"ample 4
Ninclude< iostream,h>
int main( )
{
int 8-';
8.14;
'.12;
i! (8 > ' )
{
cout
8/16/2019 Introduction to C++.docx
26/107
}
}
Lutput : 8 is greater than '
if...else statement
he general form of a simple if...else statement is,
i!( e8pression )
{
statement7%loc1;
}
else
{
statement7%loc?;
}
If the 5expression5 is true, the 5statement-bloc#$5 is executed, else
5statement-bloc#$5 is s#ipped and 5statement-bloc#'5 is executed.
E"ample 4
&oid main( )
{
int 8-';
8.14;
8/16/2019 Introduction to C++.docx
27/107
'.1O;
i! (8 > ' )
{
cout
8/16/2019 Introduction to C++.docx
28/107
{
statement7%loc ?;
}
}
else
{
statement7%loc 2;
}
if 5expression5 is false the 5statement-bloc#*5 will be executed, otherwise it
continues to perform the test for 5expression $5 . If the 5expression $5 is true
the 5statement-bloc#$5 is executed otherwise 5statement-bloc#'5 is
executed.
E"ample 4
&oid main( )
{
int a-%-c;
clrscr();
cout > a >> % >> c;
i!(a > %)
{
i!( a > c)
8/16/2019 Introduction to C++.docx
29/107
{
cout
8/16/2019 Introduction to C++.docx
30/107
else-if ladder
he general form of else-if ladder is,
i!(e8pression 1)
{
statement7%loc1;
}
else i!(e8pression ?)
{
statement7%loc?;
}
else i!(e8pression 2 )
{
statement7%loc2;
}
else
de!ault7statement;
he expression is tested from the top(of the ladder) downwards. %s soon
as the true condition is found, the statement associated with it is executed.
E"ample 4
&oid main( )
8/16/2019 Introduction to C++.docx
31/107
{
int a;
cout > a;
i!( aP4..= aPO..=)
{
cout
8/16/2019 Introduction to C++.docx
32/107
}
Points to 2emember
$. In if statement, a single statement can be included without enclosing
it into curly braces { }
?, int a . 4;
2, i!(a > 3)
3, cout
8/16/2019 Introduction to C++.docx
33/107
#o3 it 3or5s
% se=uence of statement is executed until a specified condition is true. his
se=uence of statement to be executed is #ept inside the curly
braces { } #nown as loop body. %fter every execution of loop body,
condition is chec#ed, and if it is found to be true the loop body is executed
again.
8/16/2019 Introduction to C++.docx
34/107
*. do-while loop
3ile loop
3ile loop can be address as an entr! control loop. It is completed in *
steps.
• ariable initiali?ation.( e.g int xF>M )
• condition( e.g while( xHF$>) )
• ariable increment or decrement ( x++ or x-- or xFx+' )
S!nta" 4
&aria%le initialiation ;
9hile (condition)
{
statements ;
&aria%le increment or decrement ;
}
for loop
for loop is used to execute a set of statement repeatedly until a particular
condition is satisfied. we can say it an open ended loop9 Aeneral format
is,
8/16/2019 Introduction to C++.docx
35/107
!or(initialization; condition ; increment/decrement)
{
statement7%loc;
}
In for loop we have exactly two semicolons, one after initiali?ation and
second after condition. In this loop we can have more than one initiali?ation
or incrementGdecrement, separated using comma operator. for loop can
have only one condition.
6ested for loop
8/16/2019 Introduction to C++.docx
36/107
8/16/2019 Introduction to C++.docx
37/107
It causes the control to go directly to the test-condition and then continue
the loop process. On encountering continue, cursor leave the current cycle
of loop, and starts with the next cycle.
Storage Classes in C++
!torage classes are used to specify the lifetime and scope of variables.
ow storage is allocated for variables and ow variable is treated by
complier depends on these storage classes.
hese are basically divided into 0 different types 8
$. Alobal variables
'. Bocal variables
*. Degister variables
. !tatic variables
0. &xtern variables
0lobal .ariables
hese are defined at the starting , before all function bodies and are
available throughout the program.
using namespace std;
int glo%e; @lo%al &aria%le
&oid !unc();
int main()
8/16/2019 Introduction to C++.docx
38/107
{
,,,,,
}
Local variables
hey are defined and are available within a particular scope. hey are also
called Automatic variablebecause they come into being when scope is
entered and automatically go away when the scope ends.
he #eyword auto is used, but by default all local variables are auto, so we
don5t have to explicitly add #eyword auto before variable dedaration.
/efault value of such variable is garbage.
2egister variables
his is also a type of local variable. his #eyword is used to tell the
compiler to ma#e access to this variable as fast as possible. ariables are
stored in registers to increase the access speed.
;ut you can never use or compute address of register variable and also ,
a register variable can be declared only within a bloc5, that means, you
cannot have global or static register variables.
Static .ariables
8/16/2019 Introduction to C++.docx
39/107
!tatic variables are the variables which are initiali?ed 4 allocated storage
only once at the beginning of program execution, no matter how many
times they are used and called in the program. % static variable retains its
value until the end of program.
&oid !un()
{
static int i . 1=;
i++;
cout
8/16/2019 Introduction to C++.docx
40/107
his #eyword is used to access variable in a file which is declared 4
defined in some other file, that is the existence of a global variable in one
file is declared using extern #eyword in another file.
$unctions in C++
"unctions are used to provide modularity to a program. Creating an
application using function ma#es it easier to understand, edit, chec# errors
etc.
S!nta" of $unction
return-type function-name ( parameters)
{
!unction7%od'
}
8/16/2019 Introduction to C++.docx
41/107
8/16/2019 Introduction to C++.docx
42/107
ere, a and b are sent as arguments, and " and ! are parameters which
will hold values of a and b to perform re=uired operation inside function.
• $unction bod! 4 is he part where the code statements are written.
Declaring> Defining and Calling $unction
"unction declaration, is done to tell the compiler about the existence of the
function. "unction5s return type, its name 4 parameter list is mentioned.
"unction body is written in its definition. Bets understand this with help of an
example.
Ninclude < iostream>
using namespace std;
int sum (int 8- int '); declaring !unction
int main()
{
int a . 1=;
int % . ?=;
int c . sum (a- %); calling !unction
cout
8/16/2019 Introduction to C++.docx
43/107
}
ere, initially the function is declared, without body. hen inside main()
function it is called, as the function returns sumation of two values, hence ?
is their to store the value of sum. hen, at last, function is defined, where
the body of function is mentioned.
8/16/2019 Introduction to C++.docx
44/107
calc(8);
print!("Pd"- 8);
}
&oid calc(int 8)
{
8 . 8 + 1= ;
}
Lutput : 1=
In this case the actual variable 8 is not changed, because we pass
argument by value, hence a copy of x is passed, which is changed, and
that copied value is destroyed as the function ends(goes out of scope). !o
the variable " inside main() still has a value $>.
;ut we can change this program to modify the original ", by ma#ing the
function calc&' return a value, and storing that value in x.
int calc(int 8);
int main()
{
int 8 . 1=; 8 . calc(8);
print!("Pd"- 8);
}
8/16/2019 Introduction to C++.docx
45/107
int calc(int 8)
{
8 . 8 + 1= ;
return 8;
}
Lutput : ?=
Call b! 2eference
In this we pass the address of the variable as arguments. In this case the
formal parameter can be ta#en as a reference or a pointer, in both the case
they will change the values of the original variable.
&oid calc(int $p);
int main()
{
int 8 . 1=;
calc(8); passing address o! 8 as argument
print!("Pd"- 8);
}
&oid calc(int $p)
8/16/2019 Introduction to C++.docx
46/107
{
$p . $p + 1=;
}
Lutput : ?=
6OE 4 If you do not have a prior #nowledge of pointers, do study ointers
first.
Introduction to Classes and Objects
The classes are the most important feature of C++ that leads to !ject riented
pro"rammin"# Class is a user defined data t$pe, %hich holds its o%n data mem!ers
and mem!er functions, %hich can !e accessed and used !$ creatin" instance of that
class#
The &aria!les inside class definition are called as data mem!ers and the functions
are called mem!er functions#
'imilarl$, class is just a !lue print, %hich declares and defines characteristics and
!eha&ior, namel$ data mem!ers and mem!er functions respecti&el$# nd all
o!jects of this class %ill share these characteristics and !eha&ior#
,ore about Classes
# Class name must start %ith an uppercase letter# *f class name is made of
more than one %ord, then first letter of each %ord must !e in
uppercase# Example,
class Etudent
8/16/2019 Introduction to C++.docx
47/107
Classes contain, data mem!ers and mem!er functions, and the access of these
data mem!ers and &aria!le depends on the access specifiers (discussed in net
section)#
# Class-s mem!er functions can !e defined inside the class definition or
outside the class definition#
.# Class in C++ are similar to structures in C, the onl$ difference !ein", class
defaults to pri&ate access control, %here as structure defaults to pu!lic#
/# ll the features of 0', re&ol&e around classes in C++# *nheritance,
1ncapsulation, !straction etc#
2# !jects of class holds separate copies of data mem!ers# 3e can create as
man$ o!jects of a class as %e need#
4# Classes do posses more characteristics, li5e %e can create a!stract classes,
immuta!le classes, all this %e %ill stud$ later#
Objects
Class is mere a !lueprint or a template# 6o stora"e is assi"ned %hen %e define a
class# !jects are instances of class, %hich holds the data &aria!les declared in
class and the mem!er functions %or5 on these class o!jects#
1ach o!ject has different data &aria!les# !jects are initiali7ed usin" special class
functions called Constructors# 3e %ill stud$ a!out constructors later#
nd %hene&er the o!ject is out of its scope, another special class mem!er function
called Destructor is called, to release the memor$ reser&ed !$ the o!ject# C++
8/16/2019 Introduction to C++.docx
48/107
doesn-t ha&e utomatic 8ar!a"e Collector li5e in 9, in C++ estructor
performs this tas5#
class %c
{
int 8;
&oid displa'(){} empt' !unction
};
in main()
{
%c o%*; L%*ect o! class %c created
}
Access Control in Classes
7ow before studying how to define class and its objects, lets first =uic#ly
learn what are access specifiers.
%ccess specifiers in C++ class defines the access control rules. C++ has *
new #eywords introduced, namely,
$. public
'. private
*. protected
8/16/2019 Introduction to C++.docx
49/107
8/16/2019 Introduction to C++.docx
50/107
member, they will get a compile time error. ;y default class variables and
member functions are private.
class Qri&ateccess
{
pri&ate: pri&ate access speciAer
int 8; Rata em%er Reclaration
&oid displa'(); em%er Function decaration
}
Protected
rotected, is the last access specifier, and it is similar to private, it ma#es
class member inaccessible outside the class. ;ut they can be accessed by
any subclass of that class. (If class % is inherited by class ;, then class ; is
subclass of class %.
8/16/2019 Introduction to C++.docx
51/107
3hen %e define an$ class, %e are not definin" an$ data, %e just define a structure
or a !lueprint, as to %hat the o!ject of that class t$pe %ill contain and %hat
operations can !e performed on that o!ject#
elo% is the s$nta of class definition,
class ClassSame
{
ccess speciAer:
Rata mem%ers;
em%er Functions(){}
};
ere is an eample, %e ha&e made a simple class named 'tudent %ith appropriate
mem!ers,
class Etudent{
pu%lic:
int rollno;
string name;
};
'o its clear from the s$nta and eample, class definition starts %ith the 5e$%ord
>class> follo%ed !$ the class name# Then inside the curl$ !races comes the class
!od$, that is data mem!ers and mem!er functions, %hose access is !ounded !$
8/16/2019 Introduction to C++.docx
52/107
access specifier# class definition ends %ith a semicolon, or %ith a list of o!ject
declarations#
Example :
class Etudent
{
pu%lic:
int rollno;
string name;
}-T;
ere and are the o!jects of class 'tudent, declared %ith the class definition#
3e can also declare o!jects separatel$, li5e %e declare &aria!le of primiti&e data
t$pes# *n this case the data t$pe is the class name, and &aria!le is the o!ject#
int main(){
Etudent ;
Etudent T;
}
oth and %ill ha&e their o%n copies of data mem!ers#
Accessing Data ,embers of Class
8/16/2019 Introduction to C++.docx
53/107
%ccessing a data member depends solely on the access control of that
data member. If its public, then the data member can be easily accessed
using the direct member access (,) operator with the object of that class.
If, the data member is defined as private or protected, then we cannot
access the data variables directly. hen we will have to create special
public member functions to access, use or initiali?e the private and
protected data members. hese member functions are also
called Accessors and ,utator methods or getter andsetter functions.
Accessing Public Data ,embers
"ollowing is an example to show you how to initiali?e and use the public
data members using the dot (.) operator and the respective object of class.
class Etudent
{
pu%lic:
int rollno;
string name;
};
int main()
{
Etudent ;
8/16/2019 Introduction to C++.docx
54/107
Etudent T;
,rollno.1;
,name."dam";
T,rollno.?;
T,name."Tella";
cout
8/16/2019 Introduction to C++.docx
55/107
int rollno;
pu%lic: pu%lic accessor and mutator !unctions
int getUollno()
{
return rollno;
}
&oid setUollno(int i)
{
rollno.i;
}
};
int main()
{
Etudent ;
,rollono.1; Compile time error
cout
8/16/2019 Introduction to C++.docx
56/107
8/16/2019 Introduction to C++.docx
57/107
int getVolume(); Reclaring !unction getVolume 9ith no
argument and return t'pe int,
};
If we define the function inside class then we don5t not need to declare it
first, we can directly define the function.
class Cu%e
{
pu%lic:
int side;
int getVolume()
{
return side$side$side; returns &olume o! cu%e
}
};
;ut if we plan to define the member function outside the class definition
then we must declare the function inside class definition and then define it
outside.
class Cu%e
{
8/16/2019 Introduction to C++.docx
58/107
pu%lic:
int side;
int getVolume();
}
int Cu%e :: getVolume() deAned outside class deAnition
{
return side$side$side;
}
he maine function for both the function definition will be same. Inside
main() we will create object of class, and will call the member function
using dot , operator.
int main()
{
Cu%e C1;
C1,side.3; setting side &alue
cout
8/16/2019 Introduction to C++.docx
59/107
!pes of ,ember $unctions
3e alread$ 5no% %hat mem!er functions are and %hat the$ do# 6o% lets stud$
some special mem!er functins present in the class# ?ollo%in" are different t$pes of
@em!er functions,
# 'imple functions
# 'tatic functions
.# Const functions
/# *nline functions
2# ?riend functions
Simple ,ember functions
These are the !asic mem!er function, %hich dont ha&e an$ special 5e$%ord li5e
static etc as prefi# ll the "eneral mem!er functions, %hich are of !elo% "i&en
form, are termed as simple and !asic mem!er functions#
returnt'pe !unctionSame(parameterlist)
{
!unction %od';
}
Static ,ember functions
8/16/2019 Introduction to C++.docx
60/107
'tatic is somethin" that holds its position# 'tatic is a 5e$%ord %hich can !e used
%ith data mem!ers as %ell as the mem!er functions# 3e %ill discuss this in details
later# s of no% %e %ill discuss its usa"e %ith mem!er functions onl$#
function is made static !$ usin" static 5e$%ord %ith function name# These
functions %or5 for the class as %hole rather than for a particular o!ject of a class#
*t can !e called usin" the o!ject and the direct mem!er access , operator# ut, its
more t$pical to call a static mem!er function !$ itself, usin" class name and scope
resolution :: operator#
Example :
class
{
pu%lic:
static &oid !(){};
};
int main()
{
::!(); calling mem%er !unction directl' 9ith class name
}
These functions cannot access ordinar$ data mem!ers and mem!er functions, !ut
onl$ static data mem!ers and static mem!er functions#
*t doesn-t ha&e an$ >this> 5e$%ord %hich is the reason it cannot access ordinar$
mem!ers# 3e %ill stud$ a!out >this> 5e$%ord later#
8/16/2019 Introduction to C++.docx
61/107
Const ,ember functions
3e %ill stud$ Const 5e$%ord in detail later, !ut as an introduction, Const 5e$%ord
ma5es &aria!les constant, that means once defined, there &alues can-t !e chan"ed#
3hen used %ith mem!er function, such mem!er functions can ne&er modif$ the
o!ject or its related data mem!ers#
Tasic E'nta8 o! const em%er Function
&oid !un() const {}
Inline functions
ll the mem!er functions defined inside the class definition are !$ default declared
as *nline# 3e %ill stud$ *nline ?unctions in details in the net topic#
$riend functions
?riend functions are actuall$ not class mem!er function# ?riend functions are made
to "i&e private access to nonAclass functions# Bou can declare a "lo!al function as
friend, or a mem!er function of other class as friend#
Example :
class MithFriend
{
int i;
8/16/2019 Introduction to C++.docx
62/107
pu%lic:
!riend &oid !un(); @lo%al !unction as !riend
};
&oid !un()
{
MithFriend 9!;
9!,i.1=; ccess to pri&ate data mem%er
cout
8/16/2019 Introduction to C++.docx
63/107
{
&oid !un();
};
class MithFriend
{
pri&ate:
int i;
pu%lic:
&oid getdata(); em%er !unction o! class MithFriend
!riend &oid Lther::!un(); maing !unction o! class Lther as
!riend here
!riend class Lther; maing the complete class as !riend
};
3hen %e ma5e a class as friend, all its mem!er functions automaticall$ !ecome
friend functions#
?riend ?unctions is a reason, %h$ C++ is not called as a pure !ject riented
lan"ua"e# ecause it &iolates the concept of 1ncapsulation#
Inline $unctions in C++
8/16/2019 Introduction to C++.docx
64/107
%ll the member functions defined inside the class definition are by default
declared as Inline. Bet us have some bac#ground #nowledge about these
functions.
6ou must remember reprocessors from C language. Inline functions in C+
+ do the same thing what 1acros do in C. reprocessors were not used in
C++ because they had some drawbac#s.
Inline $unctions
Inline functions are actual functions, which are copied everywhere duringcompilation, li#e preprocessor macro, so the overhead of function calling is
reduced. %ll the functions defined inside class definition are by default
inline, but you can also ma#e any non-class function inline by using
#eyword inline with them.
"or an inline function, declaration and definition must be done together. "or
example,
inline &oid !un(int a)
{
return a++;
}
Some Important points about Inline $unctions
8/16/2019 Introduction to C++.docx
65/107
$.
8/16/2019 Introduction to C++.docx
66/107
&oid setdata(int 8)
{
i.8;
}
};
ere getdata() and setdata() are inline functions, and are made to access
the private data members of the class %uto. getdata(), in this case is
called Accessor function and setdata() is a ,utator function.
here can be overlaoded %ccessor and 1utator functions too.
8/16/2019 Introduction to C++.docx
67/107
$or3ard 2eferences
%ll the inline functions are evaluated by the compiler, at the end of class
declaration.
class For9ardUe!erence
{
int i;
pu%lic:
int !() {return g()+1=;} call to undeclared !unction
int g() {return i;}
};
int main()
{
For9ardUe!erence !r;
!r,!();
}
6ou must be thin#ing that this will lead to compile time error,but in this case
it will wor#, because no inline function in a class is evaluated until the
closing braces of class declaration.
$unction Overloading
If any class have multiple functions with same names but different
parameters then they are said to be overloaded. "unction overloading
8/16/2019 Introduction to C++.docx
68/107
allows you to use the same name for different functions, to perform, either
same or different functions in the same class.
"unction overloading is usually used to enhance the readability of the
program. If you have to perform one single operation but with different
number or types of arguments, then you can simply overload the function.
-a!s to overload a function
$. ;y changing number of %rguments.
'. ;y having different types of argument.
6umber of Arguments different
In this type of function overloading we define two functions with same
names but different number of parameters of the same type. "or example,in the below mentioned program we have made two sum() functions to
return sum of two and three integers.
int sum (int 8- int ')
{
cout
8/16/2019 Introduction to C++.docx
69/107
8/16/2019 Introduction to C++.docx
70/107
dou%le sum(dou%le 8-dou%le ')
{
cout
8/16/2019 Introduction to C++.docx
71/107
{
sum(1=);
sum(1=-=);
sum(1=-1=);
}
Lutput : 1= 1= ?= "irst two function calls will produce the exact same
value.
for the third function call, y will ta#e $> as value and output will become '>.
;y setting default argument, we are also overloading the function. /efault
arguments also allow you to use the same function in different situations
just li#e function overloading.
2ules for using Default Arguments
$. Only the last argument must be given default value. 6ou cannot have
a default argument followed by non-default argument.
sum (int 8-int ');
sum (int 8-int '.=);
sum (int 8.=-int '); #his is ncorrect
'. If you default an argument, then you will have to default all the
subse=uent arguments after that.
sum (int 8-int '.=);
8/16/2019 Introduction to C++.docx
72/107
sum (int 8-int '.=-int ); #his is incorrect
sum (int 8-int '.1=-int .1=); Correct
*. 6ou can give any value a default value to argument, compatible withits datatype.
Placeolder Arguments
8/16/2019 Introduction to C++.docx
73/107
3hile definin" a contructor $ou must reme!er that the name of constructor %ill !e
same as the name of the class, and contructors ne&er ha&e return t$pe#
Constructors can !e defined either inside the class definition or outside class
definition usin" class name and scope resolution :: operator#
class
{
int i;
pu%lic:
(); Constructor declared
};
::() Constructor deAnition
{
i.1;
}
!pes of Constructors
Constructors are of three t$pes :
# efault Constructor
# 0arametri7ed Constructor
.# Cop$ Cnstructor
8/16/2019 Introduction to C++.docx
74/107
Default Constructor
efault constructor is the constructor %hich doesn-t ta5e an$ ar"ument# *t has no
parameter#
Syntax :
classname ()
{ Constructor ReAnition }
Example :
class Cu%e
{
int side;
pu%lic:
Cu%e()
{
side.1=;
}
};
int main()
{
Cu%e c;
8/16/2019 Introduction to C++.docx
75/107
cout
8/16/2019 Introduction to C++.docx
76/107
Parameteri/ed Constructor
These are the constructors %ith parameter# Dsin" this Constructor $ou can pro&ide
different &alues to data mem!ers of different o!jects, !$ passin" the appropriate
&alues as ar"ument#
Example :
class Cu%e
{
int side;
pu%lic:
Cu%e(int 8)
{
side.8;
}
};
int main()
{
Cu%e c1(1=);
Cu%e c?(?=);
Cu%e c2(2=);
cout
8/16/2019 Introduction to C++.docx
77/107
cout
8/16/2019 Introduction to C++.docx
78/107
{
rollno.8;
name."Sone";
}
Etudent(int 8- string str)
{
rollno.8 ;
name.str ;
}
};
int main()
{
Etudent (1=);
Etudent T(11-"Uam");
}
*n a!o&e case %e ha&e defined t%o constructors %ith different parameters, hence
o&erloadin" the constructors#
ne more important thin", if $ou define an$ constructor eplicitl$, then the
compiler %ill not pro&ide default constructor and $ou %ill ha&e to define it
$ourself#
8/16/2019 Introduction to C++.docx
79/107
*n the a!o&e case if %e %rite Etudent E; in main(), it %ill lead to a compile time
error, !ecause %e ha&en-t defined default constructor, and compiler %ill not
pro&ide its default constructor !ecause %e ha&e defined other parameteri7ed
constructors#
Destructors
estructor is a special class function %hich destro$s the o!ject as soon as the scope
of o!ject ends# The destructor is called automaticall$ !$ the compiler %hen the
o!ject "oes out of scope#
The s$nta for destructor is same as that for the constructor, the class name is used
for the name of destructor, %ith a tilde I si"n as prefi to it#
class
{
pu%lic:
I();
};
estructors %ill ne&er ha&e an$ ar"uments#
E"ample to see o3 Constructor and Destructor is called
class
{
()
8/16/2019 Introduction to C++.docx
80/107
{
cout
8/16/2019 Introduction to C++.docx
81/107
Single Definition for bot Default and Parameteri/ed Constructor
*n this eample %e %ill use default argument to ha&e a sin"le definition for !oth
defualt and parameteri7ed constructor#
class Rual
{
int a;
pu%lic:
Rual(int 8.=)
{
a.8;
}
};
int main()
{
Rual o%*1;
Rual o%*?(1=);
}
ere, in this pro"ram, a sin"le Constructor definition %ill ta5e care for !oth these
o!ject initiali7ations# 3e don-t need separate default and parameteri7ed
constructors#
8/16/2019 Introduction to C++.docx
82/107
Static ?e!3ord
!tatic is a #eyword in C++ used to give special characteristics to an
element. !tatic elements are allocated storage only once in a program
lifetime in static storage area. %nd they have a scope till the program
lifetime. !tatic Neyword can be used with following,
$. !tatic variable in functions
'. !tatic Class Objects
*. !tatic member ariable in class
. !tatic 1ethods in class
Static variables inside $unctions
!tatic variables when used inside function are initiali?ed only once, and
then they hold there value even through function calls.
hese static variables are stored on static storage area , not in stac#.
&oid counter()
{
static int count.=;
cout
8/16/2019 Introduction to C++.docx
83/107
{
!or(int i.=;i
8/16/2019 Introduction to C++.docx
84/107
Lutput : = = = = =
If we do not use static #eyword, the variable count, is reinitiali?ed everytime
when counter() function is called, and gets destroyed each time when
counter() functions ends. ;ut, if we ma#e it static, once initiali?ed count will
have a scope till the end of main() function and it will carry its value through
function calls too.
If you don5t initiali?e a static variable, they are by default initiali?ed to ?ero.
Static class Objects
!tatic #eyword wor#s in the same way for class objects too. Objects
declared static are allocated storage in static storage area, and have scope
till the end of program.
!tatic objects are also initiali?ed using constructors li#e other normal
objects. %ssignment to ?ero, on using static #eyword is only for primitive
datatypes, not for user defined datatypes.
class %c
{
int i;
pu%lic:
%c()
{
i.=;
cout
8/16/2019 Introduction to C++.docx
85/107
}
I%c()
{
cout
8/16/2019 Introduction to C++.docx
86/107
Lutput : constructor WSR destructor
6ou must be thin#ing, why was destructor not called upon the end of the
scope of if condition. his is because object was static, which has scope till
the program lifetime, hence destructor for this object was called when
main() exits.
Static data member in class
!tatic data members of class are those members which are shared by all
the objects. !tatic data member has a single piece of storage, and is not
available as separate copy with each object, li#e other non-static data
members.
!tatic member variables (data members) are not initialied using
constructor, because these are not dependent on object initiali?ation.
%lso, it must be initiali?ed explicitly, always outside the class. If not
initiali?ed, Bin#er will give error.
class
{
static int i;
pu%lic:
(){};
};
int ::i.1;
8/16/2019 Introduction to C++.docx
87/107
int main()
{
o%*;
cout
8/16/2019 Introduction to C++.docx
88/107
int main()
{
::!(); calling mem%er !unction directl' 9ith class name
}
hese functions cannot access ordinary data members and member
functions, but only static data members and static member functions.
It doesn5t have any this #eyword which is the reason it cannot access
ordinary members.
8/16/2019 Introduction to C++.docx
89/107
8/16/2019 Introduction to C++.docx
90/107
int const$ &;
still it has the same meaning. In this case also, v is a pointer to an int which
is const.
Const pointer
o ma#e the pointer const, we have to put the const #eyword to the right of
the $.
int 8 . 1;int$ const 9 . 8;
ere, w is a pointer, which is const, that points to an int. 7ow we can5t
change the pointer but can change the value that it points to.
6OE 4
8/16/2019 Introduction to C++.docx
91/107
8/16/2019 Introduction to C++.docx
92/107
'. "or user defined data types, returning const, will prevent its
modification.
*. emporary objects created while program execution are always of
const type.
. If a function has a non-const parameter, it cannot be passed a const
argument while ma#ing a call.
&oid t(int$) { }
If we pass aconst int$
argument, it will give error.
0. ;ut, a function which has a const type parameter, can be passed a
const type argument as well as a non-const argument.
&oid g(const int$) {}
his function can have a int$ as well as const int$ type argument.
@' Const class Data members
hese are data variables in class which are made const. hey are not
initiali?ed during declaration. heir initiali?ation occur in the constructor.
class #est
{
const int i;
pu%lic:
8/16/2019 Introduction to C++.docx
93/107
#est (int 8)
{
i.8;
}
};
int main()
{
#est t(1=);
#est s(?=);
}
In this program, i is a const data member, in every object its independent
copy is present, hence it is initiali?ed with each object using constructor.
Once initiali?ed, it cannot be changed.
' Const class Object
8/16/2019 Introduction to C++.docx
94/107
Const class ,ember function
% const member function never modifies data members in an object.
Syntax :
returnt'pe !unctionname() const;
E"ample for const Object and const ,ember function
class
{
int i;
pu%lic:
(int 8) Constructor
{ i.8; }
int !() const Constant !unction
{ i++; }
int g()
{ i++; }
};
int main()
8/16/2019 Introduction to C++.docx
95/107
{
o%*1(1=); Son const L%*ect
const o%*?(?=); Const L%*ect
o%*1,!(); So error
o%*?,!(); So error
cout
8/16/2019 Introduction to C++.docx
96/107
class X
{
int i;
muta%le int *;
pu%lic:
X()
{i.=; *.=;}
&oid !() const
{ i++; Wrror
*++; Mors- %ecause * is uta%le
}
};
int main(=
{
const X o%*;
o%*,!();
}
2eferences in C++
Eeferences are li5e constant pointers that are automaticall$ dereferenced# *t is a
ne% name "i&en to an eistin" stora"e# 'o %hen $ou are accessin" the reference,
$ou are actuall$ accessin" that stora"e#
8/16/2019 Introduction to C++.docx
97/107
int main()
{ int '.1=;
int r . '; r is a re!erence to int '
cout
8/16/2019 Introduction to C++.docx
98/107
Eeferences are "enerall$ used for function ar"ument lists and function return
&alues, just li5e pointers#
2ules for using 2eference in $unctions
# 3hen %e use reference in ar"ument list, %e must 5eep in mind that an$
chan"e to the reference inside the function %ill cause chan"e to the ori"inal
ar"ument outside th function#
# 3hen %e return a reference from a function, $ou should see that %hate&er
the reference is connected to shouldn-t "o out of scope %hen fnction ends# 1ither
ma5e that global or static
E"ample to e"plain use of 2eferences
int$ Arst (int$ 8)
{ ($8++);
return 8; EFW- 8 is outside this scope
}
int second (int 8)
{ 8++;
return 8; EFW- 8 is outside this scope
8/16/2019 Introduction to C++.docx
99/107
}
int third ()
{ int D;
return D; WUULU- scope o! D ends here
}
int !ourth ()
{ static int 8;
return 8; EFW- 8 is static- hence li&es till the end,
}
int main()
{
int a.=;
Arst(a); @BY and e8plicit
second(a); CBWS and hidden
}
3e ha&e four different functions in the a!o&e pro"ram#
8/16/2019 Introduction to C++.docx
100/107
• first() ta5es a pointer as ar"ument and returns a pointer, it %ill %or5 fine#
The returnin" pointer points to &aria!le declared outside first(), hence it %ill !e
&alid e&en after the first() ends#
• 'imilarl$, second() %ill also %or5 fine# The returnin" reference is connected
to &alid stora"e, that is int ain this case#
• ut in case of third(), %e declare a &aria!le D inside the function and tr$ to
return a reference connected to it# ut as soon as function third() ends, the local
&aria!le G is destro$ed, hence nothin" is returned#
• To remedif$ a!o&e pro!lem, %e ma5e as static in function fourth(),
"i&in" it a lifetime till main() ends, hence no% a reference connected to %ill !e
&alid %hen returned#
Const 2eference
Const reference is used in function ar"uments to pre&ent the function from
chan"in" the ar"ument#
&oid g(const int 8)
{ 8++; } WUULU
8/16/2019 Introduction to C++.docx
101/107
int main()
{
int i.1=;
g(i);
}
3e cannot chan"e the ar"ument in the function !ecause it is passed as const
reference#
Argument Passing 0uidelines
Dsuall$ call by value is used durin" funtcion call just to sa&e our o!ject or &aria!le
from !ein" chan"ed or modified, !ut %hene&er %e pass an ar"ument !$ &alue, its
ne% cop$ is created# *f %e pass an o!ject as ar"ument then a cop$ of that o!ject is
created (constructor and destructors called), %hich affects efficienc$#
ence, %e must use const reference t$pe ar"uments# 3hen %e use, const
reference, onl$ an address is passed on stac5, %hich is used inside the function and
the function cannot chan"e our ar"ument !ecause it is of const t$pe#
'o usin" const reference t$pe ar"ument reduces o&erhead and also sa&es our
ar"ument from !ein" chan"ed#
Cop! Constructor in C++
Copy Constructor is a type of constructor which is used to create a copy of
an already existing object of a class type. It is usually of the form &',
8/16/2019 Introduction to C++.docx
102/107
where L is the class name.he compiler provides a default Copy Constructor
to all the classes.
S!nta" of Cop! Constructor
class-name (class-name &)
{
, , , ,
}
%s it is used to create an object, hence it is called a constructor. %nd, it
creates a new object, which is exact copy of the existing copy, hence it is
called cop! constructor .
ointers to class members
8/16/2019 Introduction to C++.docx
103/107
Pust li#e pointers to normal variables and functions, we can have pointers
to class member functions and member variables.
Defining a pointer of class t!pe
8/16/2019 Introduction to C++.docx
104/107
8/16/2019 Introduction to C++.docx
105/107
L%*ect,$pointer#oem%er
and with pointer to object, it can be accessed by writing,
L%*ectQointer7>$pointer#oem%er
Bets ta#e an example, to understand the complete concept.
class Rata
{
pu%lic:
int a;
&oid print() { cout
8/16/2019 Introduction to C++.docx
106/107
dp7>$ptr.?=;
dp7>print();
}
Lutput : a is.1= a is.?=
he syntax is very tough, hence they are only used under special
circumstances.
Pointer to ,ember $unctions
ointers can be used to point to class5s 1ember functions.
S!nta" 4
returnt'pe (classname::$ptrname) (argumentt'pe) .
classname::!unctionname ;
;elow is an example to show how we use ppointer to member functions.
class Rata
{ pu%lic:
int ! (0oat) { return 1; }
};
int (Rata::$!p1) (0oat) . Rata::!; Reclaration and assignment
int (Rata::$!p?) (0oat); Lnl' Reclaration
int main(=
8/16/2019 Introduction to C++.docx
107/107
{
!p? . Rata::!; ssignment inside main()
}
Some Points to remember
$. 6ou can change the value and behaviour of these pointers on
runtime. hat means, you can point it to other member function or
member variable.
'. o have pointer to data member and member functions you need to
ma#e them public.