We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 204
~
SUNBEAM
0
9 Institute of Information Technology Placement filsive
oO fo
7 | Language Basic
Generally languages are classified as follows:
1. Procedure oriented programming languages.
e.g. C, Pascal etc.
2. Object Oriented Programming languages.
e.g. Simula, Smalltalk, C++, Java, C# etc.
3. Object Based Programming Languages.
e.g, ada, modula-2, visual Basic
4. Logic Oriented Programming Languages.
5. Rule Oriented Programming Languages.
6. Constraint Oriented Programming Languages.
S
Advantages of object oriented programming:
1. Code Reusability
Objects created for object oriented programs can easily be reused in other programs.
Lower Cost Of Development
, More effort is put into the object oriented analysis and design which lowers overall cost
of development.
| 3. Improved Software Maintainability
\ Since design is modular, part of the system can be updated in case of issues without a
. | Need to make large scale changes.
1] 4. Higher Quality Software
: Faster development of software and lower cost of development allows more time and
resources to be used in the verification of the software which tends to result in higher quality
software.
~wwewye VOD
Parts/Elements/Pillars of OOP model:
‘There are four major and three minor elements of object oriented programming médel.
Major means.a language without any one of these elements is not considered as object
oriented.
Following are the major pillars of OOPs:
1. Abstraction
2. Encapsulation
3. Modularity
4. Hierarchy
SuMBeam Institute of Information Technology, Pune, KaradSUNBEAM
Institute of Information Technology
Placement Iitative
as
Minor means, each of these elements is useful but not essential.
Following Are the minor pillars of OOP:
1. Typing
2. Concurrency
3. Persistence
Brief history of C++:
The C++ programming language has a history going back to 1979, when Bjarne Stroustrup
was doing work for his Ph.D. thesis. One of the language Stroustrup had the opportunity to
work with was a language called Simula, which as the name implies is a language primarily
designed for simulations. The Simula’67 language is regarded as the first language to support
the object-oriented programming paradigm. Stroustrup found that this paradigm was ve
usefui for software development, however the Simula language was far too slow for practical
use.
Shortly thereafter, he began work on "C with Classes", which as the name implies was meant
to be a superset of the C language. His goal was to add object-oriented programming into the
€ language, which was and still is a language well-respected for Its portability without
Sacrificing speed or low-level functionality.
The first C with Classes compiler was called Cfront. It was a program designed to translate C
with Classes code to ordinary C. Cfront would later be abandoned in 1993 after it became
difficult to integrate new features into it, namely C++ exceptions. Nonetheless, Cfront made
a huge impact on the implementations of future compilers and on the Unix operating system.
In 1983, the name of the language was changed from C with Classes to
CH
Data types:
Data type in any language describes three things:
1L.How much memory is required to store the data.
2.Which kind of data that memory can hold.
3.Which operations we can perform on that data.
Basically there are only two types of data types but for our convenience we will classify it into
three types
-Fundamental data types
Lvoid unknown size
2.boo! 1 byte Ican contain either true or false value ]
SunBeam Institute of Information Technology, Pune, Karadcael
ww ewww wy ev Ve VY
@ sunBesm
<= Institute of Information Technology
CHt
3.char LT byte [ASCII Compatible ]
4.wchart 2 bytes —_[ Unicode Compatible |
5.int 4 bytes
6.float 4 bytes
7.double 8 bytes
-Derived Datatypes
Latray
2.function
3.pointer
4.reference
-User Defined Data Types
1.Structure
2.Union
3.Class
Access Specifers in C++
There are three acess specifiers in c++
‘L.private:
ft
Placement Initiative
If we declare elements of the class as private then we can access these members inside same
class in which it is declared. We cannot access private members inside nonmember function.
Generally data members should be declared as private.
2.protected:
If we declare elements of the class as protected then we can access these members inside
same class in which it is declared as well as inside derived class. We cannot access protected
members outside the class,
3.public:
If we declare elements of the class as public then we can access these members inside same
class in which it is declared, inside. derived class as well as inside non member functioy.
Generally member function should be declared as public
Structure In C++
-structure is collection of related elements which get continuous memory space.
SunBeam Institute of Information Technology, Pune, Karad6 sunBeam
=, Institute of Information Technology eee
-in case of instantiation use of struct keyword is optional.
-we can write variable as well as function inside structure in c++.
-by default members of the structure are treated as a public.
-to create light weight object we should use structure.
Data member:
“Variable declared inside class is called data member.
-Data membcr is also called field, property or attribute,
f we create object then it gets single copy of the data member i.e. data member gets space
inside object.
Member function:
-Function implemented inside a class is called member function.
-Member function is also called method, operation,behavior or message.
-Member function do not get space inside object rather all the objects of same type share
single copy of member function.
Class:
-syntactically class is collection of data member and member function.
-In general ‘Class is collection of such objects which represents common structure and
‘common behavior’.
-Since object is always created by looking toward the, class is considered as @
template/model/blueprint for an object.
-class is logical entity.
-class is a user defined data type. It is also calfed abstract data type.
Object:
-Syntactically, object is variable of class.
-An entity which is having physical existence is called object.
-In object oriented way, we can define object as a instance of ciass.
-At the time of creation of abject use of class keyword is optional.
class Point pointinstance; //valid
Point pointinstance; Invalid
Some important terminology
1. Instantiation - Process of creating object from a class is called instantiation.
2. Concrete class - If class allows us to create an object of a class then it is called concrete
class.
3. Concrete method - Member function of a class which is having a body is called concrete
method.
SunBeam Institute of Information Technology, Pune, Karad
°
o
’
6
oe
ee
coeweyevyvyvuUYVYVD
~VweMweneweevvevevevevuvse
SUNBEAM *
Institute of Information Technology Placement Initatve
Cr
4. Abstract class - If class do not allows us to create an object of a class then it is called
abstract class.
5. Abstract method - Member function of a class which do not contain body is called
concrete method.
6. Message Passing - Process of calling member function on object is called message
Passing.
consider the following example
Point pt;
pt.Point::printRecord( ); //valid : Message passing
PtL.printRecord( ); INalid : Message passing
1.State - The state of an object encompasses all of the properties of the object plus the
current values of each of these properties. Vatues stored inside object is called state.
2.Behavior - Behavior is how an object acts and reacts, in terms of its state changes and
message passing. Member functions of the class represent behavior of the object.
B.ldentity - Identity is that property of an object which distinguishes it from all other
objects.
An object is an entity that has state, behavior, and identity. The structure and behavior of
similar objects are defined in their common class. The terms instance and object are
interchangeable.
Empty class and object:
A class which do not conain any member is called empty class.consider the following code.
class Empty -
{
//Empty implementation
h
According to Bjame stroustrup, to differentiate object from a class, object must get space
inside memory and it should be non zero. But compilers do optimization because there is no
use of such memory. So size of object of empty class is one byte.
SunBeam Institute of Information Technology, Pune, KaradEe SUN
® BeAm
Institute of Information Technology
sureeam Placement Iitetve
on
this pointer:
- this is a keyword in C++
- It is implicit pointer available inside every non static member function of the class, which is
used to store address of current abject.
- this is constant pointer and its general type is as follows
ClassName* const this
- this represent address c/ current object while ( *this )represents current object itself.
- Data member and member function can communicate with each other with the help of this
pointer so this is considered as connection / link between data member and member function.
- If any member function accepts parameters then this pointer is always_pass as a_first}
parameter implicitly.
- We cannot declare this as a function parameter explicitly.
- Use of this keyword is optional but we should use it.
Tf name of data member and function parameter is same then it is mandatory to use this
keyword before data member.
- Following function do not get this pointer:
M1 Global function
\2¢Static member function
w@. Friend function.
Array of Objects:
Point arrl 3 1; //Here parameterless ctor will call three times
for( int index = 0; index < 3; ++ index )
arr[ index ].printRecord();
Point arr[ 3} = { Point(10,20),Point(30,40),Point(50,60)};
//Here parameterized constructor will call three times
for( int index = 0; index < 3; ++ index )
arr{ index ].printRecord();
Namespace :
Namespace is logical term, which is used to control scope of global members. In other words
to avoid name ambiguity or name clashing or name collision we should use namespace.
int num1 = 10;
intnum1 = 20; — //error: ‘num1' : redefinition; multiple initialization
‘SunBeam Institute of Information Technology, Pune, Karad
ers
oooceecocoos ice srasvoy
eww ee Vee
~wrrrwyewevve
& SuUNBeEAm
Institute of Information Technology
SUPBEAM Placement Initiative
CH
int main void )
{
printf("Num2 %d\n",num);
retum 0;
}
As shown in above code we cannot give same name to multiple members in same scope.
Pronlem may occur, if name of elements refereed from different library and name of element
declared in same program is same. To avoid this problem, we should implement global
members inside namespace. we can write above program as follows
namespace NA
{
int num1 =
}
namespace NB
t
int num =
JINow no error
}
int main( void )
{
printf("Num2 =: %d\n",NA::num); //Num
printf(*Num2 : %d\n",NB::num1); //Num1
return 0;
3
As shown in above code, we should use namespace name and scope resolution operator to
access elements of namespace.
We can implement namespace inside scope of another namespace, It is called nested
namespace. First we will see nested namespace with different element names.
int numi = 10;
namespace NA
{
int num2 = 20;
namespace NB
is
int num3 = 30;
ee EE ee
‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
institute of Information Technology
Placement Initiative
C++
int main(void)
{
printfNum3 : Sed\n", NA::NB::numg3); JINum3
printf(*Num2 F 7 uNum2
printf("Num1 : H //Num1
return 0;
a;
Generally we use the statement that to access global variable or function we should use ::
operator.
Jn namespace topic we have discussed that to access elements of namespace we should ::
operator. Consider above code. Since num3 is member of NB namespace & NB namespace is
member of NA namespace we have written NA:NB::num3. num2 is member of NA
namespace, we have written NA:ntim2.Even though num is not a member of any
namespace we Can use :: operator with it. Meaning of this statement is that, if we declare or
implement global members without namespace it is considered as member of unnamed or
global namespace.
if we want to use any member of namespace frequently then instead of specifying
namespace name every time we can use using directive. The using directive allows the names
ina namespace to be used without the namespace name as an explicit qualifier, consider the
following code.
int num1 = 10;
pamespace NA
{
Int num2 = 20;
namespace NB
{
int num3 = 30;
ui
int main(void)
{
printf("Num1 : %d\n", unum); yNum2
using namespace NA;
‘SunBeam Institute of Information Technology, Pune, Karad
Bwoovoeooceoeo ee sce Ts e039 030SUNBEAM
= Institute of Information Technology a
or
printf("Num2 %d\n", num2); HNum2 20
printf("Num3 d %d\n", NB::num3); uma: 30
using namespace NB;
printf("Num3 fl %d\n", num3); yNum3 30
return 0;
+
We can write "Vsing namespace namespace_name" statement any number of times.
We can give same name fo the outer namespace as well as inner namespace. In this case we
cannot use ‘using' di 10 access namespace members.
namespace NA
{
int numa = 10;
namespace NA
{
int num2 = 20;
int main(void)
{
printf("Num. = %d\n", NA::num2); mun.
printf("Num2 :%d\n", NAz:NA::num2); JINum2
return 0;
+
We can give same namespace name to other namespace inside same scope.
namespace NA
{
int num = 10;
+
namespace NA
{
int num2 =
+
int main(void)
SunBeam institute of Information Technology, Pune, KaradG sunBeam
= Institute of Information Technology
printf(*Num. fl %d\n", NA::num1);
printf(*Num2, i %d\n", NA::num2);
using namespace NA;
printf("Num1 =: (%éd\n", num);
printf("Num2 : %d\n", num2);
return 0;
+
ie
Placement Initiative
we should use using statement carefully otherwise we may get unexpected results. consider
following code snippet.
namespace NA
{
int num1 = 10;
}
int main(void)
{
int num1 = 20;
using namespace NA;
printf("Num1
printf("Num1
printf("Num1
printf("Num1
return 0;
}
'f name of members of namespace is same and if we try to access it with the help of using
directive then compiler produces ambiguity error.In this case we should use fully qualified
name. consider following code.
namespace NA
{
int num = 10;
namespace NB
{
int num =
int num2
SunBeam Institute of Information Technology, Pune, Karad
10
9
°
°
3
2
6
GC
oO
°
e
o
Q
o
°
°
Q
Q
vo
Q
e
°
|
|
|
|5 SUNBEAM
9 Institute of Information Technology
Placement hitiative
) C++
J | int main(void)
y {
using namespace NA;
printf("Num1 2 %d\n",num1); JNum1.
using namespace NB:
Nprintf("Num1—:——%d\n*, numt); Hambiguity error
print"Num1 =: d\n", NBssnum}; 4uNurn. 20
printf("Num1 ——: d\n", num2); yNumn2 30
return 0;
o”V
}
We can declare using directive at local scope as well as file scope.
In following code snippet we have declared “using namespace namespace_name" statement
at local scape.
namespace NA
{
int num1 = 10;
+
void show _record(void)
{
using namespace NA;
printf("Num2 =: %d\n", num1);
3
void display_record(void)
{
using namespace NA;
printf("Num1 =: d\n", numt);
+
int main(void)
{
~~ yee wrwrvyrveve ew wewevvue
ushow_record();
isplay_record(
SunBeam Institute of Information Technology, Pune, Karad
’ "G sunBeam
Institute of Information Technology
suneeam Placement hitative
ceed
return 0;
3
IF we want to access namespace elements at multiple location then we should declare "using
Namespace namespace_name" statement at file scope. Consider the following example.
namespace NA
{
int num =
using namespace NA;
void show_record(void)
{
printf("Num2, %d\n", num
void display_record(void)
{
printf(*Num1. %d\n", num);
t
int main(void)
t
nshow_secord();
fisplay_record();
return 0;
} 5
unnamed or anonymous namespace -
In C/C++,if we dectare any global element as static then we can access such element inside
same file only. In C++ unnamed namespace or anonymous namespace is superior alternative
given for global static member declarations.
namespace
{
int num1;
SunBeam Institute of Information Technology, Pune, Karad
"Soe
oo
eooececoooecoosInstitute of Information Technology
| & SsuNnBeam
Placement Initiative
aaa
}
int main(void)
{
oO 2.0
num1 = 10;
printf("Num1. : %d\n", num’);
return 0;
i
Each unnamed namespace has an identifier, assigned and maintained by the program and
represented here by unique
above code is implicitly interpreted as follows:
namespace unique
{
vue
int numa;
3
int main(void)
af
unique::num1 = 10;
printf("Num2 2 %d\n", unique::num1);
retum 0;
wwwewvevuy
+
namespace Alias -
if name of the namespace is too lengthy then we can create alias for it. Consider the following
syntax.
namespace namespace_name
{
int num1;
+
namespace NA = namespace_name;~
int main(void)
it
~~~ ~r~wew
printf("num1 : %d\n", Ni
’ return 0;
}
Points To Remember:
) ] 1. Namespace is logical term which is used to group or organize functionally equivalent or
related code together.
—————————
| ] SunBeam Institute of Information Technology, Pune, Karad Page 13@ SUNBEAM
Institute of Information Technology Placement initiative
surmeam
lea
2. In C++, We can achieve logical modularity with the help of namespace.
3. To access members of namespace we should use scope resolution( :: Joperator.
4, We can write anyglobal variable, function, enum, structure, class as well as namespace
inside namespace.
5. We cannot write namespace inside class i.e. A namespace definition must appear either at
file scope or immediately within another namespace definition.
6. We cannot implement entry point function( main ) inside namespace.
7. Inside same as well as different file we can give same name to the multiple namespace.
8, We cannot create instance of namespace.
9. Instead of declaring global element as static we should put them inside unnamed
namespace.
‘Constructor:
Process of storing user defined value inside variable/object at the time of declaration/creation
is callec itialization.
int number = 123; //initialization
Constructor is member function of a class which is used to initialize the object.
namespace NPoint
5
class Point
{
ivate:
int xPosition;
int yPosition;
Point( void ) //constructor
{
this->xPosition = 0;
this->yPosition
+
int main(void)
{
NPoint::Point pointinstance;
//Here for pointinstance object constructor will call
SunBeam Institute of Information Technology, Pune, Karad
4
is
ecoceeccoooosocsVeuwVwuy
wwwewerwewe vee yew
SUNBEAM
Institute of Information Technology ee
an
return 0;
}
Due to following reasons constructor Is special member function
-its name is same class name
-it do not have any return type ( but we can write return statement inside constructor).
-it is not designed to call explicitly on object rather it gets call implicitly.
-in complete life cycle bject, constructor gets call only once
Types of Constructor:
C++ supports three kinds of constructor.
1. Pararneterless constructor.
2. Pararneterized constructor.
3. Default constructor.
Most of us consider copy constructor is fourth type of constructor. But it is kind of
parameterized constructor. We will discuss copy constructor separately.
Parameter less constructor: A constructor which do not take any parameter is called
parameter less constructor. parameter less constructor is also called zero parameter
constructor or user defined default constructor. |
if we create an object without passing argument then parameter less constructor gets call.
Point pt; Here for pt1 object parameterless constructor will cali
Parameterized constructor: if constructor takes parameters then it is called parameterized
constructer.
If we create an object by passing argument then parameterized constructor gets call.
Point ptl( 10, 20 ); Here for pti object parameterized constructor which is taking 2
parameters will call
Point pt2( 500 ); Here for pt2 object parameterized constructor which is taking 1 parameter
will call
How many and which kind of constructor should be exist inside a class depends on
instantiation.
Constructor calling sequence is depends on order of object declaration.
Default constructor: If class do not contain any kind of constructor then compiler provides
one constructor for the ciass it is called default constructor.
Default constructor do not perform any operation on data member declared in our class. It
look like as follows
—_——————
SunBeam Institute of Information Technology, Pune, Karad Page 15@ sunBesam
Institute of Information Technology
Placement initiative
suneeam
CH
Point( void )
t
Prempty*/
h
Compiler generated default constructor do not take any parameter i.e. compiler never
generate default parameterized constructor. If we want to create an object by passing
argument then we cannot rely on default constructor. In this case we should define
parameterized constructor inside a class.
We will see exact use of default constructor in virtual function topic.
Constructor is designed for initialization it doesn't mean we cannot call methods from it.
We cannot declare constructor as const, volatile, virtual or static. We can declare constructor
as Inline only. Inline function we will discuss fater.
Aggregate type:
ff type allows us to store multiple elements then it is called aggregate type and object is
called aggregate object.
In C language, array, structure and union is called aggregate type. Aggregate type allows us
to initialize object using initializer list. Consider the following code:
int arf } = { 10, 20, 30 };
struct point ptl = { 10, 20 };
class may be classified as aggregate type if it obeys following rule.
1. class should not contain user defined constructor.
2. Class should not contain private and protected members.
3. class should not be derived from any other class.
4. class should not contain virtual function.
Aggregate class is also called Plain Old Data struct( POD- struct )
Test your understanding:
class Point
{
private:
int xPosition;
int yPosition;
SunBeam Institute of Information Technology, Pune, Karad
oS
oe
3
3
o
Q
Q
o
a
a
oO
eo
G
Q
Qo
Q
38
o
a
a
e
a
@
|
i& sunBeam
Institute of Information Technology nS i
sureeam Plaoement Initative
C++
publi
Point( void );
Point( int value );
Point(int xPosition, int yPosition);
wuUev.0 vo
h
In following cases which constructor will call?
Point pt;
Point pt2( 10);
Point pt3( 20, 30 );
Point pt4( );
Point ptS = 40;
Point pt6 = 50, 60;
Point pt7 = (50, 60 );
Point pt8 = { 70, 80 };
Point pt9( 90, 100 );
Point pt10 = pi
10. Point* ptr;
~~wrryrwwrwrvwrvwevvvvw vue
) | As per our requirement, we can use any access specifier for constructor. If we declare
constructor as private or protected then we can create instance of class only inside member
function. If we declare constructor as public then we can create instance of class inside|
) | member function as well as non member function,
Note: Generally we should public access specifier for constructor.
Constructors member initializer list
) | c++ allows us to initialize data members of the class inside constructors body as well
| | constructors member initializer list. If we initialize data members inside constructors pod|
gc
} | SunBeam Institute of Information Technology, Pune, Karad Page 17@& SUNBEAM
surBeAm
Institute of Information Technology
Placement itiative
a
then it gets executed in the same order in which it is written inside constructor body. For
example:
class Test
{
private:
int x;
int ys
int z;
public:
Test(void)
{
this->z = this->y:
this->y = this->x;
this->x = 20;
hb
int main(void)
{
Test test; //10,garbage value,garbage value
return 0;
+
If we initialize data members inside constructors member initializer list then it gets executed
according to the order of data member declaration.
For example:
class Test
{
private:
int x;
int y;
int 2:
public:
Test(void) : zly), x(10), yx)
{ }
h
int main(void)
{
Iictor's member initializer list
‘SunBeam Institute of Information Technology, Pune, Karad
8
booceoeocooooococoesSUNBEAM
Institute of Information Technology
Placement hitative
on
1/10,10,10
return 0; }
we cannot initialize array inside constructors member initializer list. It is limitation of
constructors member initializer list.
we can use constructors member initializer list and constructor body together. In this case
cuntime environment executes constructors member initializer list first and tren constructors
body.
Note:Generally we should use constructor's member initializer to initialize data members. In
case of modularity constructors member initializer list must appear in definition part only.
Default argumentis):
int sum(int numd, int num2)
{
return num + num2;
a
int sum(int num1, int num2, int num3)
{
retum num] + num2 + num3;
}
int sum(int num1, int num2, int num3, int num4 )
t
return num] + num2 + num3 + num4;
+
int maintvoid)
{
int result = 0;
result = sum(10, 20);
result = sum(10, 20, 30);
result = sumt0, 20, 30, 40);
return
}
we consider above functions then its implementation is logically equivalent. Since all the
functions having same name and same type of parameters then we can reuse its
implementation by assigning some default values to the parameters. For example
SunBeam Institute of Information Technology, Pune, Karad Page 19
”& sunBesam
= Institute of Information Technology
sureeal Placement Initiative
C++
int sum(int num, int num2, int num3 = 0, int num4 = 0)
it
retum num1 + num2 + num3 + num4;
}
int main(void)
it
int result = 0;
result = sum(10, 20);
result = sum(10, 20, 30);
result = sum(10, 20, 30, 40);
return 0;
3
Default values assign to the parameters of function is called default argument and function
parameter is called optional parameter. In above code 0 is default argument and num3 and
num4 are the optional parameters. We cannot assign default arguments randomly. If we want
to assign default arqument to the parameter then it is necessary to assign default argument
to all its right side parameters.
We can assign default arguments to parameters of any member function as. well as not
member function.
Note:In case of modularity, we must specify default arguments in declarations part only.
Constructor Chaining:
Process of calling constructor from another constructor is called constructor chaining. If we
want to reuse implementation of existing constructor then we can use this feature. Since c++
support default argument, it do not support constructor. chaining.
In C+4 we cannot call constructor with pointer or object explicitly. But it is possible to call to
constructor explicitly.
Constant:
I-value( Locator Value ): 2
Expressions that refer to memory locations are called "I-value" expressions. An |-value
represents a storage region's "locator" value, or a "left" value, implying that it can appear on
the left of the equal sign ( =). L-values are often identifiers.
In following example, x is an I-value because it persists beyond the expression that defines it.
int main)
{
intx = 34
SunBeam Institute of Information Technology, Pune, KaradD SUNBEAM
ay) Institute of Information Technology
eT
Placement initiative
CHt
cout << x << endl;
y
or
3
) | rvalue( Reference Value)
An rvalue is a temporary value that does not persist beyond the expression that uses it. All |-
| values are rvalues but not all values are I-values.
} | In above example, the expression 3 + 4 is an r-value because It evaluates to a temporary
value that does not persist beyond the expression that defines it.
d
y | Readonly Members:
Once initialized, if we don’t want modify state of an object then we should declare
) | variable/object as a constant. In C++ it is compulsory to initialize constant variable.
9 | Note:Generally we should declare function parameter as a constant.
) | constant Data Member:
» if we dont want to modify state of the data member inside any member function of the class(
including contructor ) then we should declare data member as a constant.
| Note:It is compulsory to initialize constant data member inside constructors member
p | initializer is.
b class Math
vyt
private:
y const double Pl; //constant data member
) | public:
) Math(void) : PI(3.14)
{
, Mtthis->Pl = 3.142; JNot allowed
Constant Member function:
If we don’t want to modify state on current object inside member function then we should
| | declare member function as constant. We can declare only such function as a constant which
get this pointer. Since global function do not get this pointer, we cannot declare global
function as a constant.
SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
Institute of Information Technology
Placemant Initiative
on
Non constant member function always get this pointer of following type:
ClassName* const this;
Constant member function always get this pointer of following type:
const ClassName* const this;
‘As shown in above declaration. if we deciare member function as constant then current object
is considered as const object
inside that member function,
Class Test
‘f
private:
int number;
public:
Test(void) : number(10)
{ }
/Mest* const this = &testinstance;
void increment()
t
this->number = this->number +1; /allowed
}
IIconst Test* const this = Atestinstance;
int getNumber(void)const
{
Ifthis->number = this->number + 1; //Not allowed
return this->number;
Int main(vold)
t
Test testinstance;
return 0;
+
With the help of non constant object we can invoke constant as well as non constant member
function.
mutable is a keyword in c++, which allows us to modify state of non constant data member
inside constant member function.
class Test
‘SunBeam Institute of Infarmation Technology, Pune, Karad
2
wewooceooceoeooos=> ew YY YY we eV eV ev SS OS
SUNBEAM
Institute of Information Technology Placement iatve
an
private:
const int num1;
const int num2;
mutabie int count;
public:
Test(const int num1 = 0, const in num2 = 0) : numi{nurn), num2(num2)
t
this->count =
}
void print(void)const
{
this->count = this->count + 1; //allowed
cout<< "Count : — * << this->count << endl;
cout <<"Numl: " << this->num1 << end;
cout << "Num2: "<< this->num2 << endl;
he
int main(void)
{
Test testinstance;
testinstance. print();
testinstance.print();
return 0;
+
We can declare object of class as a constant, Using canstant object we can call only constant
member function,
const, volatile and mutable is called Access modifier.
Reference:
typdef is feature of C language which allows us to create alias for the existing data type.
e.9. typedef unsigned int size_t;
size:t size = sizeoft int );
Reference is feature of C++ which allows to create alias for existing object.
eg. intnuml = 10;
SunBeam Institute of Information Technology, Pune, Karad
2G@ SUNBEAM
Institute of Information Technology — +
srseam
CHt
inté& numa,
In above code, num2 is reference variable where num1 is referent variable. Once initialized
we cannot change referent of reference.
int num1 = 10;
int num2 = 20;
int& num3 = num1; —_//num3 is reference variable for num1;
num3 = num2; ITkere we are not changing reference .ather copy value from
num2 into num:
Since references are implicitly considered as a constant pointer, it is compulsory to initialize
references. Following code illustrate how references are implicitly const and pointer.
class Test
{
private:
double& num3;
public:
IN is compulsory to initialize references in ctors member initilaizer list
Test(double& num2) : num3( num2 )
{ }
}
int main(void)
{
double numi = 10;
Test testinstance( num );
size_t size = sizeof(testinstance); _// 4 bytes,
return 0;
My e
Even though data member is a type of double, size of an object is 4 bytes, it means that
references are implicitly treated as a pointer. References need to initialize inside ctors
member initializer list it means that references are implicitly treated as const.
int num = 10;
int& num2 = num1;
Now we can treat above statement as follows:
int num = 10;
SunBeam Institute of Information Technology, Pune, Karad
2
QHROSOOHOOFTECSCOCOOCA™H S3067)
SU.
vu
~~~r~rwrvrvvrvrvvuevvuvv eV
SUNBEAM
Institute of Information Technology
C++
int& num2 = num; Hint® const num2 = &num1;
i.e. References are automatically dereferenced constant pointer variables.
In following code i have used constant in combination with reference.
int num1 = 10;
int& num2 = num1;
const int& num3 = num1;
Here we can read as well as modify state of num1 via num2 but we cannot modify state via
num3.
References are not designed to use independently rather it is designed to pass and return
object from function by reference.
Note:Generally we should not return local variable by reference. In thi
declare local variable as static.
Points To Remember:
Reference is derived data t)
2.Reference is ct tocreate alas for the object.
case we should
6.We cannot create reference to constant.
7.We cannot create array of references.
&.We can create reference to pointer, array, function as well as object.
9.We can pass object to the function by value, by address and by reference.
10.With the help of reference we cannot save the memory rather we can minimize
complexities of pointer,
Test your understanding:
How will you create reference to array?
What is the difference between pointer and reference?
Macro vs inline Function:
Macro: A macro is short form of macro instruction.
It is a rule or pattem that specifies how a certain sequence of characters should be mapped
to a replacement output sequence of characters according to a defined procedure. In short,
ca re eal
SunBeam Institute of Information Technology, Pune, Karad Page 25
25SUNBEAM
Institute of Information Technology
Placement nialve
Gr
symbolic constant is also called macro. The mapping process that transforms a macro use
into a specific sequence is known as macro expansion. Preprocessor is program which
expands the macro.
Preprocessor performs two main task:
L.Expands the macro and
2.Removes the comments which included in .c file
There are two types of macros, object-like and function-like, Object-like macros do not take
parameters; function-like macros do
Consider the example of object like macro
#define PI 3.142
Consider the example of function like macro
#define SQUARE( number) number * number
int main(void)
{
int number = 5;
cout << SQUARE(number) << endl;
return 0;
Several identifiers are predefined, and expand to produce special information.
__LINE__ A decimal constant containing the current source line number.
__FILE__A string literal containing the name of the file being compiled.
_DATE__A string literal containing the date of compilation, in the form "Mmmm dd yyy"
__TIME__A string literal containing the time of compilation, in the form "hh:mm:ss"
Inline Function:
Giving call to the function is always overhead to the compiler because each time a function is
called, a significant amount of overhead is generated by the calling and return mechanism.
‘Typically, arguments are pushed onto the stack and various registers are saved when a
function is called, and then restored when the function returns. The trouble is that thes
instructions take time.
‘An inline function is one for which the compiler copies the code from the function definition
directly into the code of the calling function rather than creating a separate set o'
in memory. instead of transferring control to and from the function code segment, a modified
SunBeam Institute of Information Technology, Pune, Karad
SBeooegcecoceceooooro¢~
G& SUNBEAM
= Institute of Information Technology Plecoment nilane
ina
copy of the function body may be substituted directly for the function call. In this way, the
performance overhead of a function call is avoided.
To declare function as inline we shouid use inline keyword.
inline int max( int num1, int num2 )
{
return num1 > num2? num1 : num2;
}
If we implement member function inside structure/class then it is by default treated as
inline.If we define functions globaly then we must specify inline keyword explicitly. Consider
the following code.
class Point
t
private:
int xPosition;
int yPosition;
public:
inline Point();
inline void pr
~~ r~wrervrerye ey ye wwe
inline Point::Point()
{
this->xPosition = 0;
this->yPosition = 0;
i}
) | inline void Point::printRecord()
{
, cout << "x Position : "<< this->xPosition << endl;
, cout << "Y Position : "<< this->yPosition << endl;
y
"J int main(void)
yt
Point ptt;
ptl.printRecord();
return 0;
}
SunBeam Institute of Information Technology, Pune, Karad
aSUNBEAM
Institute of Information Technology
Placement Initiative
as
We can declare constructor as inline only.
The inline specifier is only a suggestion/request to the compiler that an inline expansion can
be performed; the compiler is free to ignore the suggestion.
In following condition, function cannot be classified as inline
Lif function contains a code which leads to larger executables.
2.1 we implement function using recursion.
3.If we implement function using loop.
Note:If we declare function as inline then we cannot divide class declaration and definition in
multiple files.
Test your understanding
Why inline functions are hazardous?
string clas:
Cas well as C++ programming language supports strings but string is not a fundamental
data type in it Standard Template Library. contains class ‘basic_string’ which allows us to
handle the string. string is typedef of basic_string. nema aaa
typedef basic_string string.
‘basic_string’ class is declared in string( #include)header file. Lets see how to use it.
string name;
cout<<"Enter your name :
cin>>name;
cout<<"Name <> number;
}
Void print_result(const int& result)
{
cout << "Result : "<< result << endl;
}
int main(void)
{
SunBeam Institute of Information Technology, Pune, Karad@ SUNBEAM
Institute of Information Technology Bie
int num1;
saccept secord(num2);
int num2;
saccept_record(num2);
if (num2 == 0)
throw string("Divide By Zero Exception");
int result = num / num2;
cout << "Result: " << result << endl;
}
catch ( string ex)
{
cout << ex << endl;
}
retum 0;
iz
We can write try catch block inside another try as well as catch block, Outer catch block can
handle exception which are unhand-led by the inner catch block but catch block of inner try
cannot handle exception which are unhand-led by outer catch block.
If we do not handle thrown exception then C++ runtime implicitly gives call to
inate” Function which implicitly gives call to the ‘std::aburt' function which stops
execution of program abnormally.in this case we should write such a catch block which can
handle all kind of exception thrown by user. A catch block which can handle all types q
exception is called generic catch block,
catch(...)
{
JF Inside generic catch block*/
+
If we want to use generic as well as specific catch handler together then generic catch]
handler must be the last handler.
In C++, we can throw exception from outside try block via function. Consider the following
example:
void accept_record(int& number)
‘SunBeam Institute of Information Technology, Pune, Karad
30
eogceocooo0scocsdchee ene ewe oe ete
SUNBEAM
Institute of Information Technology
C++
cout << "Enter number
cin >> number;
}
int calculate(int num1, int num2)
{
if (num2 == 0)
throw string("Divide By Zero Exception");
retum num! / num2:
}
void print_result(const int& result)
{
cout << "Result : "<empty())
throw string(“List is empty");
else
itop0
7
class Stack.
{
private:
LinkedList collection;
public:
void pop(void)throw( string )
{
try
{
collection.deleteFirst();
SunBeam Institute of Information Technology, Pune, KaradSUNBEAM a
Institute of Information Technology
catch (string e)
{
throw string("Stack is full HException chaining
i c
Stack Unwin
In the C++ exception mechanism, control moves from the throw statement to the first catch
statement that can handle the thrown type. When the catch statement is reached, all ofthe |
automatic variables that are in scope between the throw and catch statements are destroyed
in a process that is known as stack unwinding. 3
In stack unwinding, execution proceeds as follows: 8
L.Control reaches the try statement by normal sequential execution, The guarded section in
the try block is executed. a
2.If no exception is thrown during execution of the guarded section, the catch clauses that
catch clause that follows the associated try block. c
3.If a matching handler is still not found, or if an exception occurs during the unwinding (2
process but before the handter gets control, the predefined run-time function terminate +
called. if an exception occurs after the exception is thrown but before the unwind begins,
terminate is called.
o
4.f a matching catch handler is found the process of unwinding stack begins. This involves
the destruction of all automatic objects that were fully constructed—but not yet destructed—
between the beginning of the try block that is associated with the catch handler and the
throw site of the exception. Destruction occurs in reverse order of construction, The catch
handler is executed and the program resumes execution after the last handler—that is, at the
first statement or construct that is not a catch handler.
‘Types of Function:
An operation denotes a service that a class offers to its clients. Client typically performs five
kinds of operations on an object.These functions allows us to write loosely coupled class.
1. Selector: an operation that accesses the state of an object but does not alter the state.
Selector function is also called inspector function.
a a
‘SunBeam Institute of Information Technology, Pune, Karad Page 34
eoecocoegogence
g
eoogc~wwrwye ev BOVEY
& sunBeam
= Institute of Information Technology —
aa
int getReal( void )const
{
return this->_real;
}
Generally we should declare inspector function as a constant.
2.Modifier: an operation that alters the state of an object. Modifier function is also called
mutator function.
void setReal( const int real )
t
this->_real = real;
3. Iterator: an operation that permits all parts of an object to be accessed in some well-
defined order.
4, Constructor: an operation that initializes an object.
5. Destructor: an operation that deinitializes an object.
Header Guard:
In case of repeated inclusion of headers, if we want to replace contents of header only once
then we should use header guard.Header guard is also called #include guard or macro guard.
Header guards are implemented by using three preprocessor directives in a header file. Two
are placed at the beginning of the file, before any pertinent code. The last is placed at the
end of the file,
#ifndef unique_symbol
#define unique_symbol
#endif
The symbol used is not crucial, but it must be unique. It is traditional to use all capital letters
for the symbol. Only letters, numbers and the underscore character can be used in the
symbols. No other punctuation is allowed. A very common symbol is to use the name of the
header file, converting the -h suffix to a
SunBeam Institute of Information Technology, Pune, KaradInstitute of Information Technology
Placement Initatve
@ SUNBEAM
C++
Consider the Complex.h header file with header guard as follows:
#ifndef — COMPLEX_H
#define COMPLEX_H
class Complex
{
private:
int real;
int imag;
public:
int getReal()const;
void setReal( const int real );
oy
endif
Modular approach:
If we want to divide code into multiple files then class declaration should appear in header file
and member function definition should appear in source file. We should define all globaj
functions in Main.cpp file.
‘To define functions globally, we should use following format:
ReturnType ClassName::MemberFunctionName( ... )
Points To Remember:
1.We must specify default arguments only in declaration part only( .h file ).
2.Constructors member initializer list must be appear in definition part only( .cpp ).
3.const keyword must be appear in declaration as well as definition part( .h & .cpp ).
4.static keyword must be appear in declaration part only( .h file ).
5.Global definition for static data member must be appear in source file( .cpp ).
6.Friend keyword must be appear in declaration part only.( .h )
7.virtual keyword must be appear in declaration part only( .h file ).
———
‘SunBeam Institute of Information Technology, Pune, Karad@ SUNBEAM
Institute of Information Technology
SUTBEAM Prcement Initiative
wut
fg
8,We should not define pure virtual function inside source file.
9,Exception specification list can be appeared in declaration as well as definition. But it must
appear in declaration,
10.User defined header files should be included using double quotes( #include*Complex.h" ).
11.In case of multiple files,we should use following sequence of header files.
i,all C language standard header files.
ii.all C++ language standard header files.
iliall user defined header files.
ve
Modularity:
-Process of dividing complex system into modules which can be compiled separately, bu
which have connections with other modules is called modularity.
-It is major pillar of oops.
-Modilarity helps to minimize module dependancy.
-In C++, we can achieve logical modularity with the help of namespace and physical
modularity with the help of multiple files.
Abstraction:
-Process of getting essential characteristics of an object is called abstra
-An abstraction focuses on the outside view of an object.
-Abstraction focuses on the essential characteristics of some object, relative to the perspective
of the viewer.
kinds of abstractions include the following:
Entity abstraction =>An object that represents a useful model of a problem domain q
solution domain entity
Action abstraction =>An object that provides a generalized set of operations, all of which
)] perform the same kind of function.
) | Virtual machine abstraction => An object that groups operations that are all used by some
superior level of control, or
) | operations that all use some junior-level set of operations
) | Coincidental abstraction => An object that packages a set of operations that have
relation to each other
~ vyeyevwrvewevvuvvv COU Y
) | Encapsulation:
Abstraction and encapsulation are complementary concepts: Abstraction focuses on the
observable behavior of an object, whereas encapsulation focuses on the implementation that
Gives rise to this behavior.
————
, | SunBeam Institute of Information Technology, Pune, Karad Page 37
aee SUNBEAM
® Ee
Institute of Information Technology
suMBeAm Placement Inialive
CH
-Encapsulation is the process of compartmentalizing the elements of an abstraction that
constitute its structure and behavior or binding of data and code together is called
encapsulation.
-Encapsulation hides the details of the implementation of an object.
Information Hiding t
It is the process of hiding all the secrets of an object that do not contribute to its essential
characteristics. Generally we can hide data/information with the help of private or protected
access specifier.
Data Security.
Process of giving control access to the members of class is called data security. To achieve
data security first encapsulate variable and function inside a class and then the help of access
specifiers give access to the data members using getter and setter method.
class Account
{
private:
float balance;
public:
void withdraw( float amount )
{
if( amount >= 100 )
this->_balance = this->balance - amount;
else
throw Exception("Invalid amount”);
Function Overloading:
If implementation of function is Jogicaily equivalent then we should give same name to the
function. If we want to give sami the function then we must obey following rules:
‘Lnumber of parameters pass to the function must be different.
void sum( int num1, int num2 ){ }
void sum( int num1, int num2, intnum3 ){ } — //allowed
2.1f number of parameters are same then type of at least one parameter must be different.
void sum( int num1, int num2 ){ +
void sum( int num1, double num2 }{_} Jfallowed
SunBeam Institute of Information Technology, Pune, Karad Page 38
38
eococeeoocoocoocoosG sunBesam
= Institute of Information Technology
SUTBEAM Placement Intiative
0.9 9090
a
3.|f number of parameters are same then order of type of parameter must be different.
void sum( int num1, floatnum2){ —}
void sum( float num1, intnum2){ } — //allowed
2
9v
4,0n the basis of retum type we cannot give same name to the function. i.e. return type is
not considered.
void sum( int num1, int num2 ){ }
int sum( int num, int num2){ } JINot allowed
Process of writing such functions which is having same name but different signature is called
function overloading.Functions which are taking part into function overloading are called
overloded function. In case of overloading functions must be exist inside same scope. Except
main function and destructor, we can overload any global function as well as member
function.
Since ANSI has not defined any strict specification on return type, catching values from the
function are optional. so return type is not considered at the time of overloading.
9
Test Your Understanding
1.What will be the output of following program?
void print(int number)
{
wevvuvwvvsy
wr
cout << "int: "<< number << endl;
+
void print(double number)
{
cout<< "double : "<< number << endl;
print( 10 );
print( 10.5 );
print( 10.5f );
2.What will be the output of following program?
void print(int number)
t
) | SunBeam institute of Information Technology, Pune, KaradQO
SUNBEAM
Institute of Information Technology Pena iene
CHt
* << number << endl;
Chena
is
void print(float number)
{
Q-
cout << "float: * << number << endi;
°
print( 10);
°
print( 10.5 );
print( 10.5 );
Coeococogoooso Coo ooo ETOSdO0°9%
3.What will be the output of following program?
void print(int number)
{
cout << "int: “<< number << endl;
a
void print(int® number)
cout <<"int& =: " << number << endl;
print( 10 );
int number = 10;
print( number );
4.What will be the output of following program?
void print(boo! object)
{
cout << "bool : * << object << endi;
}
void print(char object)
{
cout << "char 7 "<< object << endl;
+
SunBeam Institute of Information Technology, Pune, Karad
40SUNBEAM
institute of Information Technology
oF
print true );
print( ‘A’ );
print( 65 );
5.What will be the output of following program?
void print(int numa = 0)
{
cout << “int: "<< num1 << endl;
+
void print(int numi, int num2 = 0)
cout << “int : “ <
#include
using namespace std;
int main(void)
{
auto_ptr autoPointer(new int());
*autoPointer = 10;
cout << "Value: "<< *autoPointer << endl;
return 0;
‘Test your understanding:
1. int ptr = new int();
2. Int ptr = new int( 3 );
3. int* ptr = new int! 3 J;
SunBeam Institute of Information Technology, Pune, Karad
“0& SuUNBeam ray |
= Institute of Information Technology Se
er
Whatis the difference between malloc and new?
Destructor: 0
A member function of class that has the same name as the class and is prepended with ~ lO
operator is called destructor. It is us > clean up after an object of a class is no longer in
the scope of program segment. Consider the syntax for destructor: ~ oO
~Point( void) _/Adestructor for the Point class
{
} a)
There are two situations in which a destructor is calied. The first is when an object is
destroyed under “normal” conditions, e.g., when it goes out of scope or is explicitly deleted. |
The second is when an object is destroyed by the exception-handling mechanism during the lo
stack-unwinding part of exception propagation.
if we do not define destructor for the class then compiler provides one destructor for th
class by default. It is called default destrucotr. Default destructor always does the job o|
deinitialiation only. ey
On exit from function or block, Objects created in that function are destroyed by the compiler
automatically. But an object might have an accumulated resources (dynamic memory, disk 4:
blocks, network connections etc. during its life time. These resources are stored in the
objects data members and are manipulated by the member functions. When the object
destroyed, it ry that the resources held by the object are released because abject is
no longer accessible. Because compller isn't aware of the resources held by the object, it is
responsibility of object to release such resources. To help an object in doing so, on exit from
function, destructor is called on all objects created statically{7h other words, to reléase
operating system resources held by the object we should write destructor inside class\,
Consider the following code snippet:
namespace NString
{
class String
{
private:
unsigned int length;
char* buffer
‘SunBeam Institute of Information Technology, Pune, Karad
esogcoooococoosO
v
G SUNBeEam
== Institute of Information Technology
suneeam
o
Placement Initatve
on
publi
String(unsigned int length = 0 )//etor
{
uTODO
vy
}
~String(void)//dtor
{
if (this->buffer != NULL)
{
delete[] this->buffer;
this->buffer = NULL;
Points To Remember:
17To Prevent resource leak we should use destructor.
2.Destructor calling sequence is exactly opposite of constructor calling sequence( in array too
).
3,Since destructor do not take any parameter we cannot overload
4.We can declare destructor as inline and virtual only. ~
5.Even though destructor is designed to call implicitly, we can call it explicitly too.
6.if we try to create object using new then constructor gets call and if we try to delete that
object using delete
operator then destructor gets call. Consider following example:
~~ywwewvwrvevevvevvy eV
String* ptr = new String); _{fttere ctor will call implicitly
) delete ptr; /fHere dtor will call implicitly
YT if we create an instance with the help of placement new operator then we cannot deallocate
) ] memory of an object using delete operator. if we do not use delete operator then destructor
will not be call. But to avoid resource leak we need to call destructor explicitly. Consider the
1] following code.
char arr[30);
SunBeam Institute of Information Technology, Pune, Katad
' 51—
q@ SUNBEAM
— Institute of Information Technofogy
surBeam Placement itiative
BD.
on
What is the difference between malloc and new?
Destructor:
‘A member function of class that has the same name as the class and is prepended with ~
operator is called destructor, It is used to do clean up after an object of a cfass is no longer in_
f program segment. Consider the syntax for destructor:
~Point( void) —_//destructor for the Point class
{
QO
oo
}
There are two situations in which a destructor is called. The first is when an object is
destroyed under "normal" conditions, e.g., when it goes out of scope or is explicitly deleted.
The second is when an object is destroyed by t indling mechanism during the
stack-unwinding part of exception propagation:
co
If we do not define destructor for the class then compiler provides one destructor for tHe
class by default. It is called default destrucotr. Default destructor always does the job oJ
deinitialiation only.
Goods
On exit from function or block, Objects created in that function are destroyed by the compiler
automatically. But an obj mulated resources (dynarric memory, disk
blocks, network connections etc )during its life time. These resources are stored in the
objects data members and are maniputated by the member functions. When the object 5
destroyed, cessary that the resources held by the object are released because object is
no longer acce ssible. Because compiler isn't aware of the resources held by the object, it is
responsibility of object to release Such resources. To help an object in doing so, on exit from
function, destructor is called on all objects created statically. [Tn other words, to release
‘operating system resources held by the object we should write destructor inside class\
Consider the following code snippet:
Cooo
namespace NString
{
class String
{
private:
unsigned int length
char* buffer;
‘SunBeam Institute of Information Technology, Pune, Karad
50
eooceccoooce ce