Low Level Design: Kapil Yadav

Download as pdf or txt
Download as pdf or txt
You are on page 1of 154

Low

Level
= Design
- Kapil Yadav

- OOPs concepts

- Design Principles

- Design Patterns
Kapil Yadav
-

INDEX

1 .
Classes and
objects .

2- Access Modifiers in Ctt .


public

Private (friend class and
friend fume] .

→ Protected

3 . Constructor


Default

Parameterized

copy
4. static
keyword
5 .
This keyword
6 .

New keyword
7. Const
keyword
8- Final
keyword
9.
Explicit keyword

10 .
Inheritance
Inheritance
single

Multiple

Inheritance
→ Inheritance
Multilevel

Hierarchical Inheritance

Hybrid Inheritance .

11 "

Polymorphism

Compile Time
Polymorphism
Function
overloading


operator overloading
Kapil Yadav

polymorphism
→ Run time

virtual Functions

12 .
Encapsulation

13 .
Data Abstraction

1. OOPS DESIGN PRINCIPLES



DRY
• KISS
• YAGNI

2. COHESION & COUPLING


3. CQS
4. SOLID

OOPS DESIGN PATTERN


Pattern :
17
Factory Method
Design
-

2. SINGLETON DESIGN PATTERN : -

Builder
3.
Design Pattern
Design Pattern
4. Observer
5 Abstract
.

Factory Design

linkedin.com/in/kapilyadav22
Kapil Yadav
-

class : -

Blueprint

→ state /Property /field/data member
design / type
*m⑦ behaviour / function / data function .

Humans hand

→§
Ex - 2
state /properties
Leg
2

↓ 2
eyes
behaviour → walk eat
, speak , .

Architect class ,
gives Blueprint
→ is the
using
Blueprint ,
we make the house is object .

memory / space
takes class does 't
Object

.
,

Object is an implementation / seal


entity/
instance of class .

→ class is a
logical component .


Object takes
memory from heap .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

Access Modifiers in C++ : -

One of the main features of 00ps is data


Hiding .

Data
Hiding
: -
Data
hiding refers to
restricting access

to data members of a class .


This is to prevent other

functions and classes from tampering with the class


data .

→ The access modifiers of C++ allows us to determine

which class members are accessible to other classes and

functions ,
and which are not .

→ There are 3
types of access modifiers available in
C++ .

I. Public

2 .
Private
3. Protected

By default ,
The access modifier of the members will be Private .

1. Public :
keyword used create
The
public is to
public
-

members (data and functions] .

accessible
The
public members from part of the

are
any
program .

The public members be accessed from the


anywhere in

can
program
using
direct
memory
access
operator C.) with the
object
of that class .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

Private Access Modifier : -

The
private keyword is used to create
private members

(data and
functions ] .


The private members can
only be accessed from
within the class .


However , friend classes and friend functions can access

private members .

data members of class


we the
private

can access a

indirectly using the public member functions of the

class .

linkedin.com/in/kapilyadav22
Kapil Yadav

Friend class ? -
A friend class can access private and
class it
protected members of other in which is

defined as friend .
It is sometimes used to allow
a
particular class to access
private members of
other class .

linkedin.com/in/kapilyadav22
Kapil Yadav

Friend Function : -

contains

usually the
objects as
argument .

→ It cannot access the data members


directly, we need object name
-
.

member name to access the data members .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

Protected Access Modifier : -

→ Protected Access Modifier is similar to


private access modifier ,

→ But the difference is


protected members can be access

within the class and from the desired class as well .

linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav

CONSTRUCTOR.com/stnectoris a special method that is invoked


automatically
at the time
of object creation .

initialize data
objects

It is used to the members new
of .

return
Constructors don't have
type

any
.

Constructor have class


itself
→ the
same name as .


don't
If we
specify a constructor, C++
compiler generates
a default constructor for object .


It should be placed in public section
of
class .

→ It can be overloaded .

Constructors in C++

Default Parameterized copy


we can do constructor private .
But what will

happen ?

linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav

→ Do constructor returns
any
value ?
No constructor does not return value
,
any
.

→ when there is no
copy
constructor found compiler
,

its constructor
supply own
copy
.

our
→ Human Kapil =
Chitti 11 copy constructor invoked .

→ Human Kapil ; → Default copy constructor invoked .

Our

Kapil
=
chilli 11 copy constructor not invoked ✗ .

constructor invoked ✓
→ Human Kapil (chilli ) 11 copy
our
.


when create & in line > then
we
copy
same
copy
constructor
assignment invoked but in
copy
constructor
,

doesn't invoke .

COPYConst-tor.tt constructor is member


copy a

function that
initializes an
object using another

class
object of same .

do need constructor ?
Why we
copy

provides
C++ default copy constructor and
assignment
class
operator with .

class doesn't contains need to


pointers these is

If a
,
no

constructor and
write
copy assignment operator .

→ But when we have


pointers / members which dynamically
get initialized at men time
,
the default copy constructor

copies this member with the address


of dynamically
allocated and not seal this
memory a
copy of
memory .

both the
Now
objects points to the

,
same
memory,
and
changes in one
reflects in another object .

→ The
Major disastrous effect is, when we delete one

of these
objects ,
another object still
points the to

same
memory ,
that
leak
will be a
dangling pointer ,

and
memory
is also
possible in this approach .

teak when
Memory create in
→ → It occurs we a
memory
heap and
forget to delete it .

int *
ptr =
( into) mallee ( sizeofcint));

→ so we
,
need to define our own
copy
constructor

only if an
object has
pointers or
any
runtime
allocation of the resources like filehandle,
a network connection , etc .
Output of above
program
will be 10 . we modified the
value of -61
using set value Go ] , but
changes also reflected
in t2 .

NOTE : -
The default copy
constructor creates
only
shallow
copy
.

→ User -

defined copy
constructor can creates Deep
copy .
→ To handle the case
,
we can either do

assignment
write
operator overloading
constructor
,
or we can

our own
copy
.

Copy constructor only invoked when create


→ we

an
object and assign it with other
object
in same line .

Test E3 =
-4 ;

declaration & then assignment


ofdo first
→ But in case ,

need
we to
assignment operator overloading .

test tics) ,
1-2 ;

tz tl
=
;

overloading assignment

while operator, we must check

for self assignment .


otherwise
assigning an
object to

itself may
lead to unexpected zesults .

ex -

tz =
tz ;

do self check
→ To avoid it
,
we
assignment .

if( this ! It)

{
=

{ aptr-alt.pt );
Shallow
copy shallow
object
:
In is
copy
-

an
,

created data all variables


by simply copying the
oy
of the
original object .

→ It works fine untill there is no variables of


the
object are defined in the heap memory .


If some variables are
dynamically allocated
memory
from heap section
,
then the copied object variable

will also
reference the same
memory
location .

will

This create
ambiguity and sun -
time emos
,

dangling pointer .

implicitly creates constructor


NOTE : C++ compiler a
copy
-

and overloads operator in order to


,
assignment
perform shallow
copy
at
compile time .
created
Deep copy
: -
An
object is
by copying
data
of all variables, and it also allocates
similar sesourees with the same value
memory
to the
object .

→ In order to perform Deep copy , we need to

explicitly define the


copy
constructor, and
assign
dynamic memory
as well, if required .

Also it
required allocate
dynamicallyother
→ is to
,

to the variables in the Constructors,


memory
as well .
Constructor Delegation

→ It is useful for a constructor to be able to

call another constructor of the same class ,


this feature is called constructor
Delegation .

In the above code first two lines are common ,

✗ -0 ,
y
-0
,
leading to code duplication .

→ we can create an into fame & can place


common it & call it from both
part in can the

Constructors .

→ But it not readable and it


during
is can be call

the normal execution flow this


,
means init needs to
take care
of new initialization & reinitialized'm .

→ However, C++ constructor


delegation provides an
elegant
solution of it .
INITIALIZER LIST : Initializes list is used in
initializing
the data members of class The list members
a
of
.

to be initialized is indicated with constructor as

comma -

separated list
followed by a colon .

initializes list



There are situations where
initialization of data
members inside the constructor doesn't work
and initializes list must be used .

such
Following are cases : -

1) For initialization of non-static const data members:


const data members must be initialized using
initializes list .

→ Reason for initializing the const data member in

initializes list is because is allocated


memory
no

separately for const data member, it is folded


in table need
the
symbol due to which we

to initialize it in the initialize list .


2. For initialization of reference members:

inside constructor like


→ we cannot
initialize -
t

-t=t ✗
3) For initialization of member objects which do not have default constructor:

If class one have default constructor and
,
object of
class one is data member two then there is
a
of ,
no

need
of initializes list .

But if default constructor is not there in class one
,

initialize
" "
we must use
initializes list to a .
4) For initialization of base class members :
parameterized class be
constructor
of base
only
→ The can

called initializes list


using .
5) When constructor’s parameter name is same as data member
6.) For Performance Reason

-5
"

-
I

OUTPUT:
Base parameterised constructor
Base copy constructor
Base default constructor
Base assignment operator
My class parameter constructor

2 3

OUTPUT:
Base parameterised constructor
Base copy constructor
Base copy constructor
My class parameter constructor
Structure Padding I
It is to
speed CPO optimization
-

way up
a .

structure that adds


padding is a
concept the one or

more
empty bytes between the
memory address to

align the data in


memory .

{
1

OUTPUT 12 ( not 7)
why
=

a b- -
i i i i e -
-

O 1 2 34 5 6 7 8 9 10 11
struct Base {
Chara
;
int p;
char b
;

9 - - -
P P P P b - -
-

O 1 2 34 5 6 7 8 9 10 11

I at
→ The
processor does not read
byte a time . It

reads one word at a time .

→ what does one word mean ?


for processor, processor seats
4
→ 32 bit
bytes at time ,
-

I word clock
=
4
bytes .
in 1
cycle .


for 64-bit
processor, it seats 8
bytes at a time
,
I word =

dbytes.in 1 clock
cycle .

WHY STRUCTURE PADDING ?


ex -
street student
E char a
; 11 I
byte
11
chart
;
I
byte
int g 114 bytes
3
?⃝
If we have 32 -

bit
processor then ,
the pictorial
sepxsentation memory for
the the atone
of
structure would be :
-

6
I
a

1st CPU
→ In
cycle ,
one
byte of a, one
byte of 6 ,

be
and 2
bytes of c can accessed

need CPU first


cycles
→ To access c we 2 . In
,

cycle , first 2
bytes & in second
cycle ,
another two .

want variable it
suppose only
→ we to access C
, ,
can

be access in 1 CPU
cycle ,
because its
size is
46yd,
but Here it is
taking 2 CPU
cycles .

structure
padding concept
→ to
Due this reason , was

introduced , CPU
to save the
cycles .

structure
padding automatically

is done by the

compiler .

data slots 9
How
gets memory
1
Byte
=
can be stored at
multiple of 1
memory
slot .

stored at multiple of
2
Byte can

slot
be
.
2
memory
4
Bytes can be stored at
multiple of 4
memory
slot .

stored
8
Bytes can be at
multiple of d
memory
slot .
How to avoid structure
Padding in C ?

It is an inbuilt process that is
automatically
the need avoid
done
by compiler . Sometimes we to

it as it makes the
size of structure
greater
than of structure members
the
size the .

We avoid it in two :
can
ways
-

packed directive
Using ttpoagma
°
.

Using attribute .
Abstract class : _

Pure virtual function : -


A do
nothing function is
pure
virtual
function .

C-✗ → if i want to declare a


fine inside the class i,
can do it

like ÷

class Person

{ public :

void fun cc) ;


3


if i dont want to
initialize the function fun
anywhere .

Udo
void funds 03
nothing fane
__ .

A
NOTE :-
we cannot create an
object of those classes
which have do
nothing fine .

→ But we can create a child class and access the

nothing function
do .

compulsory override the do


nothing function
→ It is to

in child class .

→ But , if derived class base class


we access the
using
pointer ,
then
by early binding funds of base class
will be called we want to avoid it so we
, ,

will made the fund) virtual .

funcO=#ñ7_
M

Pure virtual function .



If we do not override the pure virtual function in
derived class then derived class also becomes
,

abstract class .

→ An abstract class can have Constructors .


An abstract class in C++ can also be defined
struct
using keyword
.

struct Person {
eg .

virtual void funds -0 ;


y

⑦ 1) what is Abstract class ?


Anis D- Abstract class és a class in which there is
atleast one
pure virtual function ,
and we

cannot instantiate abstract class ( we cannot

of abstract class ]
create
object .

⑨ 2) Abstract class ?
why we use

Aris 2) If from same


something
there is common or

category and we can use them multiple classes


but information Abstract
class
individually
does not make
the

sense / Use of
inside
it
any
.

G-✗ → Name ,
Address, Phone Number is the information
inside Person Abstract class, but
only
this is of no use .
Name Address, Phone No
Person
-

< ¥
student
Faculty
Roll
salary
no

Person information in student ,


faculty
→ we can use

class
,
common information will be store at
single
place .

→ our efforts will be seduced .

→ Architecture will be maintabk .

→ Also we need to
define the purse virtual function in
child class .
Template : -

Template is a
keyword used to define
function template and class template .

→ It is a
way
to make our function or class
generalize as far as data
type is concern .
class Template :
-
class template is also known as

class
generic _

class class class { };


template type
- >
_ name

Instance class
of : -

class
type otj ;
< >
_ name
Type casting / Type conversion : _

Type casting is
basically a conversion from one

to
type another .

automatically

be done
It in two
by
:
can
ways
the compiler and
manually by the
programmer
.

two
types
?
There of type conversion -

are

1.
Implicit type conversion :
-
also known as
• '
automatic
type conversion .

data
automatically converted from typeto
→ It one

another with external need


any by programmer .

→ All data
type is
automatically upgraded to the
largest type without
losing any information
.

boot → chare → short int → int -3

unsigned int →
long →
unsigned
loose
→ It
possible for implicit conversions to
is

information, signs can be lost ( when signed is

implicitly converted to
unsigned ) and overflow ,

can occur ( when long long is implicitly converted


to float ) .
2.
Explicit Type Conversion :
-

→ It is user defined . user can


typecast the aesult
to make particular data
it
of a
type
.

done
In C++ it can be
by two ways :
-

Conversion
by assignment


conversion
by cast operator

done
Conversion
by assignment : This is
by
-

explicitly defining the


required type in
front
of expression in
parenthesis .

Syntax : -

ctg.pe) expression .

date to which the


where
type indicates the
type
final result is converted .
(2) Conversion
using
Cast operator A :
-
cast

operator is an
unary operator
which forces
data to another
one
type be converted into
data
type .

C++
supports four types of casting : -

1- Static cast

cast
2.
Dynamic
3- Const cast

4. Reinterpret cast

static
1. cast : -

It is a
compile-time cast that

converts data to
one
type another .

→ It does not check at runtime, whether the


cast is valid or invalid .
Thus its a user

that
responsibility to ensure the conversion was

safe and valid .

Syntax : static castanea


datatype > (expression;
-
- -

G) why to use static - cast when


implicit conversion is

involved ?
Ans ) cast is hard to find in code but
Because C-
style ,
we

static cast
can search -

keyword .
2. Use static_cast when conversion between types is provided through conversion
operator or conversion constructor

We should typecast line 22 and 23 using static_cast as we have used in line 24 and 25
3. Static cast is more restrictive than C-Style implicit cast.
Example - char* to int* is allowed in C style implicit cast but not with static_cast.

→ B ar

I I 111
C

needed allowed for only


byte for
→ we one C we were
,

one
particular block ,
but after typecasting ,
we
got
nearest also , which
access to
bytes were not

allowed .
( we can
corrupt memory , segmentation fault] .

4. static_cast avoid cast from derived to private base


pointer.
5. Use for all upcasts, but never use for confused down cast.

The above program will compiled successfully, that should not happen, we
have wrongly downcast, we should use dynamic cast in this case.
6. static_cast should be preferred when converting to void* OR from void*

Bottom Line:

1. For compatible type conversion, such as float to int.


2.For conversion operator and conversion constructors.
3. To avoid unrelated pointer conversion.
4. Avoids derived to private base pointer conversion.
5. Use for all up-cast but never use for confused down-cast
because there are no runtime checks performed for static_cast
conversions.
6. Intensions are more clear in C++ stlye cast (express your intent
better and make code review easier).
7. Finding is easy.
8.Error found at compile time.
Dynamic cast: used
In
dynamic casting is mainly
C++ ,

for safe down


casting at time sun .

work
dynamic cast, be
→ must
To on there one

virtual function in the base class .


works class
A dynamic - cast
only polymorphic base because

it uses this information to decide safe down


casting
.

Syntax : -

dynamic castnewtype Expression)


_
>

→ If the cast is success full , dynamic _ cast returns a

value of type new


type
_
.


If the cast
fails and
newtype is a
pointer type ,

setwens null of that


it a
pointer type .

→ If the cast
fails and
newtype is a reference type ,

it throws an
exception that matches a handler of
bad cast
type Std : :
_

Down
casting base class
pointer Cor reference)
:
Casting
-

to a derived class
pointer (or referenced is known as

clash
down
casting .
Base class → Derived

Up casting Casting desired class


pointer Corsrefeoence)
:
a
-

base class Cor reference ) is


to a
pointer known as

Derived class Base class


updating
. 2 → .

this has time overhead, because
using cast seen

time
it checks object types at men using
RTTI

( Run time
type information ).

If that will cast to
we are sure we never
wrong
cast and
object then we should always avoid this use

static _
cast .
Const Cast ; _

used to
change
→ Const cast can be the const or

volatile qualifiers of pointers or


references .

const cast (v )
Syntax
: -
_
at >

where T must be a
pointer reference
,
or
pointer -

to
-

member
type .
"
2. when we need to call some 3
party library
taking variables /
it const
where is
object as non -

but not
changing that .
reinterpret_cast
It is to convert
pointer of data type into
→ use some
a

a pointer of another data type

not check if the and data



does
It
pointer type pointed
not
by the
pointer is same or .

It does not action converts


type

have
any It
simply
.

the
pointer type .


It takes
only one parameter .

→ It is used when we want to work with bits .

k Y
3
y
y Y
7-
8 C
y
to
11
→ The result
of a
reinterpret - cast cannot

safely be used for anything other than


value
being cast back to its
original .


If this cast then it
we use
type of
become non -

portable product .

Because it works with bits


,
we are
directly
accessing hardware
,
so architecture can be different .

x 4

y y

c y
b 4
Kapil Yadav

STATIC KEYWORD : -

↳ static variables : variables in a


function ,

variables in a class

class and functions


static Members of class : -

objects
in a class .

class static member is accessed class


In
using

, ,

not
object .

class Human {

static ént count ;

Human C)
{ count tt ;

y
3; 11 initialize static member of class Human

int Human : : count -0


;

int main C)
E coat <<
Human : : count -
Lendl ;

ng

Q ? Can static data member


I access without
creating an

object ?
Anis .
Yes .

linkedin.com/in/kapilyadav22
Kapil Yadav

Static function → can


change static Data Member .
.

Cannot static Data Member


change the value
of non -
.
Kapil Yadav

NOTE : -
A non
-
static member function can
modify
a static data member as
long as the data member 's

visibility allows it .

keyword method

we cannot use this in static .

Q? why main function in Java is static ?


And

linkedin.com/in/kapilyadav22
Kapil Yadav

THIS
keyword :
-


Object Pointer A pointer contains address
of
-

called Pointer
an
object is
object .

local
this
object pointer in every
→ is a

instance member
function containing address
of the caller
object .

→ this
pointer cannot be
modify .

caller
→ 9T is used to refer object in member

function .

Friend functions do not have this pointer



,

because
friends are not members of a class .

member
functions how this
pointer
Only
.

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

NEW KEYWORD : -

→ The new is a
memory
allocation operator ,

which is used to allocate at the


memory
runtime .

→ The
memory initialized by
the new operator is

allocated in a
heap .

returns
It the
starting address of the

memory,
variable
which
get assigned to the .

Syntax type variable new


type (parameter list) ;
-
=
-

variable
Type datatype of
• -

a .


variable -
name of the variable .

parameter - list -

is the list of values that are

initialized to a variable .

4M£ HAT
int

IS
*
pts

MALLOC
=
new

?
int ;

,☒☒
( → Malbec ) is a function that allocates
memory
Cir
at

the runtime .

Syntax variable name


Ctypeiamalfoccsizeofctype));

type
-
-
-

variable
type it és the
datatype of

: the .


variable -
name : it defines the name of the variable

that points to the


memory .

(type *) for that


typecasting
• : It is used so we can

get the
pointer of specified type
a that

to the
points memory
.

linkedin.com/in/kapilyadav22
Kapil Yadav

NOTE :
-
The mallocc ) function returns the void pointer ,

$0
typecasting is
required to
assign a different
type to the
pointer The sizeof
.
operator is

required in the mallee function as the Malbec)

function returns the raw


memory ,
so the
sizeofc)
operator will tell the Malloch) function ,
how

much
memory
is
required for the allocation .

Allocation New
→ Memory using

delete p ;

linkedin.com/in/kapilyadav22
Kapil Yadav

Allocation mallee
Memory using
: -


If the sufficient memory is not available ,
mallee function returns the NULL
pointer .


de allocate
using free
Allocated can be
memory
function .

linkedin.com/in/kapilyadav22
Kapil Yadav

Difference between New and Maller


EW MALLOC

1. New
operator construct 1 . Mallee is a
function ,
it does

(it calls the constructor


an
object not call the .

constructor to
initialize
an
object .

2. delete operator to
destroy
2.
free function to deallocate
the
the
object .

memory .

3. new is an
operator 3 . It is predefined function
a

in stdlib.tn header file .

4. new can be overloaded . 4 . Mallock ) cannot be overloaded .

5-
If sufficient memory is not 5 . Malloch ) will seteem a NULL

available , new will throw pointers .

an
exception

6. we need to
specify 6
. We need to
specify number
allocated
number of objects .

of bytes
to be .

7. allocated be reallocated
memory by new 7 . It can
using
cannot be resized .
ocallocc)
function .

8. Execution time of new is 8 . E T


-
is more than new .

less than mallee

linkedin.com/in/kapilyadav22
Kapil Yadav

FINAL
keyword : _

→ a-+11 allows built-in


facility to
prevent
overriding of virtual function using final specifier .

overriding final
'
error -

functions
'

'

derive
error : -
cannot
from
'
final
' '
base '
Base in
' '
derived Derived
type

linkedin.com/in/kapilyadav22
Kapil Yadav

CONST KEYWORD ! -

→ Const
keywords used to define the constant
value that cannot
change during program
execution .

Use of const
keyword with different parameters : -


Use const variable

const with
Use
pointers

Use const with variables


pointer


Use const with function arguments

Use const with class member functions

class data members



Use const with .

Use class
objects

const with .

1. Consent variable
const int a- 20 ;

a -_ at 105
OUTPUT : -
error .

2. Const pointer
cannot address of const
we
change the the

pointer after its


initialization ,
which means the

pointer will
alwaysis point to the same address

once the pointer initialized as the const

pointer .

linkedin.com/in/kapilyadav22
Kapil Yadav

3. Pointer to constant variable

→ It means pointer points to the value of


a const variable that cannot
change .

Const into a;
]→ both pointer
are
to

char constant variable


constancy ;
Kapil Yadav

4. Constant function Arguments

linkedin.com/in/kapilyadav22
Kapil Yadav

5. Const
pointer pointing to a const variable : _

const
Syntax const datatypes varname ;
-
Kapil Yadav

6. Pass const
argument value to a non const
parameter of
- -

a function cause error : -

'
→ •
into ?
from
'
error : -
invalid conversion const intro to

For return Tetum


7. const
type : the
type of
-

the function is const and so it returns a

const value to
integer us .

→ There will be no issue whether

we
pass const or non
-

const
variable to the
function because
the value will be oeteerned

by the
function will be

constant
automatically .

As the
the
argument of
function is non
-
const .

linkedin.com/in/kapilyadav22
Kapil Yadav

8. For return
const
type and const
parameter : -

→ Here ,
both const and non -
const values can be

passed as the const


parameter to the
function ,

but not allowed to


we are then
change the
value
of
a
passed variable because the
parameter
is const .

Otherwise
,
we will face the error .

"

y is a const war its value can't be


changed .

linkedin.com/in/kapilyadav22
Kapil Yadav

Inheritance ? -

In C++, there are 5


types of Inheritance .

1.
Single
2. Multilevel
3. Hierarchical
4.
Multiple 3- Not in Java
5-
Hybrid
17 Base class
Single : -


☒ → derived class

output : 35 60

linkedin.com/in/kapilyadav22
Kapil Yadav

2) Multilevel 1-

Car

t
Toyota


Innova

linkedin.com/in/kapilyadav22
Kapil Yadav

37 Hierarchical ?

Employee

< ]

Intern FTE

linkedin.com/in/kapilyadav22
Kapil Yadav

Multiples speaks speaks .

MOM DAD

cH%D
classes
There Be
ambiguity the Base

can ,
when

functions have same name to soothe this : -

use
scope resolution operator .

scope
g→ oesolution
operator
Kapil Yadav

Hybrid ?
-

Vehicle

car derived from Vehicle

Car
Racing
Ferrari derived from Cart
*
Racing
Ferrari

linkedin.com/in/kapilyadav22
Kapil Yadav

ADVANTAGES : -

Reusability

code .

→ don't
Improves code
readability as we need to

rewrite the code code 100k$ Cleaner and


same
again ,
Treatable .

Inheritance classes
supports extensibility
→ as new can

classes
be
easily added to
existing
.

linkedin.com/in/kapilyadav22
Kapil Yadav

POLYMORPHISM : _

POLY MORPH
↓ ↓

Forms
Many .

→ In Ctt
, polymorphism is
mainly divided into two
types : -


Compile-time polymorphism .


Runtime Polymorphism .

Polymorphism

N
L

Compile Time Run Time

✓ ☒ ✓
Virtual
Function Operator
Functions
Overloading Overloading
1. Compile-time polymorphism : -
This
type of polymorphism
is achieved
by function overloading or
operator
overloading .

Function
Overloading
• : -

→ when there are


multiple functions with the same name

but different parameters ,


then the functions are said to be

overloaded .

Functions be overloaded
by
→ •
can .

changing the number of arguments


OR / AND
Kapil Yadav

changing the
type of arguments

.

linkedin.com/in/kapilyadav22
Kapil Yadav

Q) Can we overload main method ?


To overload main() function in C++, it is necessary to use class and declare the
main as member function. Note that main is not reserved word in programming
languages like C, C++, Java and C#. For example, we can declare a variable
whose name is main, try below example:

linkedin.com/in/kapilyadav22
Kapil Yadav

Operator Overloading : -

with
C++ has
ability
the to
provide the operators a

special meaning for a data


type, this
ability is known

as operator overloading
.

How to overload theoperator :-


To overload an
operator a operator function
,
is defined
inside a class .

class class

{
-
name

% "ᵗ" Pⁿʰ " "

return
type operator Cargs)

:
3;

Kapil Yadav
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav

R-ntmeymrp.cm?-

It is achieved
by function overriding .

Function
Overriding :

-

derived class
Function
overriding has

occurs when a a

definition for one


of the member functions of the base

class . That base function is said to te overrides .

Rules →
Must do inheritance .

→ same
function name / same
parameter .

⑦7 can we override static method ?


Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav

Function ?
Virtual A virtual function is member
-

function ,
which is declare within a base class and

is overridden derived class


by a .

→ when refer to a derived class object using a


we

reference to the base class can call


pointer a or
, we

a virtual function for that object and execute


the desired class 's version of the function .

Run-time
They mainly use to achieve
→ are

polymorphism The resolving


. of function call is done at
runtime .

Functions declared virtual


with
keyword
→ are a

in the base class .

Points to remember ? -

1. virtual functions cannot be static .

2. Virtual function can be a friend function of


another class .

3 .

They are
always defined in the base class and

class (
may / maynot
overridden in a derived . we

override in the derived class , optional ) .

4. A class have virtual destructor, but it


may
cannot have a virtual constructor .

linkedin.com/in/kapilyadav22
Kapil Yadav

OUTPUT -
This is call to
parent class area

→ To resolve the issue of function overriding ,

we use virtual function .

linkedin.com/in/kapilyadav22
Kapil Yadav

OUTPUT : 25
Square area :
-
.

linkedin.com/in/kapilyadav22
Kapil Yadav
Use of Virtual Function ?

It allows us to create a list
of base class pointers
and call methods derived class without
of any
even

knowing the kind of derived class


object .


working of virtual functions (concepts of VTABZE and

VPTR) .

If a class contains a virtual function then the

compiler itself does two


things .

If the class is created then


1 .

object of a

virtual pointer CVPTR) is inserted as a data


member of the class to point to VTABLE of
that class .

For each new


object created , a new virtual

pointer is inserted as a data member of that


virtual
class .

pointer is inherited
by derived
classes . .

Irrespective of not ,
2 .

object is created or

class contains as member static


array
a a

of function pointers called VTABLE .

Virtual Table -
A table created at compile time for
derived
every single class
containing the most versions

of virtual function only .

A virtual table contains


entry for

one

each virtual
function that can be
class
called
by objects of the .

linkedin.com/in/kapilyadav22
Kapil Yadav

virtual functions of

we can not access non

derived base
class
through class pointer .

NOTE : -
There are non virtual function in base
class ,
which are also in derived class then
,

base class function will be called , because


checks
in
earlynotbinding , compiler for object
type for object contents .

linkedin.com/in/kapilyadav22
Kapil Yadav

Virtual Destructor :-

Deleting a derived class

object using a
pointer of base class
type
that
has a non -
virtual destructor oesults in undefined
behaviour .

OUTPUT
constructing
: -
base

constructing derived

Destructing base

linkedin.com/in/kapilyadav22
Kapil Yadav

class used make


NOTE :
-
The base
pointer was to
class
the derived
object .

Destructor has to be made virtual otherwise


,

Derive Destructor will not call .

OUTPUT ? -

constructing base

derived
constructing
derived
Destructing
Destructing base
Kapil Yadav

⑦7 what about virtual constructor ?


Because when constructor of
It is not possible .
a

a class is executed there is no virtual table

in the
memory , means no virtual pointer defined
yet .

,
so constructor should
always be non -
virtual .

Because not
the
object created virtual

is
,

construction is impossible .


The compiler must know the type of object
before creating it .

Constructors
'
Error -

cannot be declared virtual ?


Kapil Yadav

Encapsulation : -

Encapsulation is defined as
wrapping up
of data and information under single
a unit .

Role of access
specifiers in encapsulation : -

The
process of implementing encapsulation can be scut divided
-

into two
steps : -

1. The data members should be labeled the


as
private using
private access specifiers .
Kapil Yadav

2. The member function which manipulates the data members

should be labeled as
public using the public access specifier .

→ Data encapsulation led to the important OOP


concept of
data
hiding .

tread " " "


→ we can write
only or write
only methods
data
to
implement hiding .

linkedin.com/in/kapilyadav22
Kapil Yadav

Abstraction ? Date abstraction is


process of providing
-
a

only the essential details to the outside world

details
and
hiding the internal

C++
provides great level of abstraction for

a . ex -

pow function is used to calculate the power of


a number without
knowing the
algorithm the function
follows .

Data Abstraction be achieved in two :


can
ways
-

••
Abstraction classes
using .


Abstraction in header files .

linkedin.com/in/kapilyadav22
Kapil Yadav

not allowed
directly
→ to
we are access
my,z
however them member
function
using
, we can access

of the class .

Advantages of Data Abstraction 2-

→ A does not need to write the low level


programmer
code .

→ Data abstraction avoids code duplication .

→ Increases Zeus
ability .


Implementation details class
of the are
protected from
the inadvertent user level errors .

linkedin.com/in/kapilyadav22
Kapil Yadav ①

OOPS DESIGN PRINCIPLES

Clean code ? →
easily readable
by other
developers .

Why ?
How ?

meaningful variable name
, function ,
class etc .

→ comments .

→ Modular

functions

short,

→ structured , readable , simple .

DESIGN PRINCIPLES : _

DRY Don't
repeat yourself
→ :
.

→ Kiss
keep it simple stupid
:
.


Abstraction :

Curly 's law


→ :

Boy Scout law ÷



Do better code
quality than what it was
-
.

Features of ?
Good
Design
-

l . Code Reuse : -

'

is
2.
Extensibility
:
change the
only constant
thing
_

in
programmer
's life ?

linkedin.com/in/kapilyadav22
Kapil Yadav

Naming Intension
revealing
→ -
names .


descriptive names .

-
int ✗
int getsumc ) ; a

~ ✗
b
int
getanswe.ro ; int

② lines]
Verb
Function Name dedicate
single
→ -
short to task
, ,
.


should have fewer arg cements ( Use Helper function ) .

• sort , several
, swap, pow .


Ward 's principle
-

Class Name
-

Noun

descriptive
meaningful


intent
revealing
-

linkedin.com/in/kapilyadav22 RCnMartin_
Kapil Yadav

DRY PRINCIPLE ( Don't repeat Yourself)

law variable should


Curly 's → A mean one
thing ,
and

one
thing only .

② KISS ( Keep it
simple stupid)

if (a)
{ if (b)
{ ifcc)
{ if (d)
{ 3
else {3
3
}
3


if (a && 6 && c && d) is
simple .

Benefits ? -

easy
to read
/ understand .


less time to code .

Bugs chances less


are .

debug / modify / update


linkedin.com/in/kapilyadav22
?⃝
Kapil Yadav

③ YAGNI : -
You ain't
gonna
need it .

"

Always implement things which are


actually
needed
just foresee
"
not the ones
, you .


Don't
engineering
Do over .

Benefits : -


Slave time .


concise code .

the root of all Evils



Preoptimisalin is .

Boy -
Scout Law ? -
The code
quality tends to
degrade
with each
change .
-

(tech debt .

'

leave behind better state
Always the code in a

found
"
than it
you .

linkedin.com/in/kapilyadav22
Kapil Yadav

COHESION & COUPLING : _

Cohesion related &


: -
It is the
degree of how
strongly
focused are the various responsibilities of a module .

→ Maximum cohesion .

Coupling
: -
It is the degree to which each module depend
on other modules .

HUMAN → CAR


Required low
coupling .

Command -

Query separation :(CQS)

Command the state but doesn't return



changes any
value .

Query return the stale without


changing the state
→ .

CQS → It states that method should be


every
a

command that performs an action, or a


query
that returns data to the caller, but not both .

linkedin.com/in/kapilyadav22
Kapil Yadav

Is there
exception of CQS ?
any

SOLID -
a set of principles .

S
single responsibility principle
-
.

0
Open closed
principle
-
-
.

L -
Liskov Substitution Principle
I Interface Segregation Principle
-

D-
Dependency Inversion Principle .

Single Responsibility principle :


-

class should have


A
just one reason to
change .

→ module ( module set functions class


Any of
means a
, ,

code ) should
package ,
source have a reason to
change by
only one actor .

have class have


Let's
say
we a
Employee ,
some

function calculate
salary ,
calculate hours , savec-mpdate.CI .

Calculates
alary C) CFO
-

calculatehours C) -

Technical
savec-mpdato.CI HR
-

linkedin.com/in/kapilyadav22
Kapil Yadav

used and it
If calculates
alanya by
→ is CFO
acquired
a method
getRegularHours O and make a
change in

will also calculate


getregulartloursc] ,
it
change in

Hours C) ,
which is
managed by someone else .

linkedin.com/in/kapilyadav22
Kapil Yadav

here class
→ what
happened was ,
one
exposed two or three

different methods ,
which were
corresponding to different
stakeholders of the software .

One Actor doesn't have to know about the other

actor, but still


change in the one them is
ofthe
reflected the other .

It is
voélating Single
Responsibility Principle .

Single Responsibility that


'

principle the code



means
, you
writing
code
are
, if that
requested change in one

stakeholder ,
which
fulfill one business
Requirement ,

till then it is
fine .

class have
That means ou r can more than one
public
method as
long as the
change in those
public method
is
requested by one stakeholder / group of stakeholders .

→ Create 3
different class ,
the calculation
of salary
doesn't
depend
need to know about / doesn't need on method
,
any
which is used in calculate hours .

By decomposing one class into multiple classes, we

can
actually adhere
single
sits in
oesponsiblity ,
where
the business
requirement one
particular
class , and request to
change those
logics comes from
one actor
only .

OPEN -
CLOSED PRINCIPLE
"

software entities such as classes, modules , functions etc ,
.

should be
open for extension
,
but closed for modification .

functionality should be
by

Any new implemented


classes, of
adding new attributes and methods, instead

changing the current ones or


existing ones .

Meyer originated

Bertrand the term OCP .

→ Robert c. Martin considered this as most important


principle .

Implementation Guidelines : -

→ The
simplest way to apply OCP is to
implement the

new
functionality on new derived classes .

→ Allow clients to class


access the
original with

abstract interface .

WHY OCP ?

Not
If followed

End
testing the entire
functionality

up
QA need test flow

Team to the entire .

linkedin.com/in/kapilyadav22

Costly Process for the
Organization
Breaks well
single roesponsibility

the as .

→ Maintenance overheads increase the classes


on .

1-

doesn't
It 's
design allow behaviour

to extend the unless

we
change the code .
for ex -

if we want to add new

sensormodel , we have to
change distance sensor class to

accommodate the new


functionality ,

by defining

we start what we want a distancesensor to

do below
in
general .
In code ,
Distance sensor is
generic, it

doesn't have a model


, therefore it doesn't make
any
sense

to concrete instance it
of
a .

Therefore we defined , Distance sensor as a


pure
abstract

class or in
javea we can
say interface .
→ when we create
specializations of
the interface for
,
each

Distance sensor model that need,


the
everytime
we
of
we want to add new sensor
,
we can create a new

child class ,
that implements the distance sensors interface
without
changing any existing code .

linkedin.com/in/kapilyadav22
LISKOV SUBSTITUTION PRINCIPLE ( LSP)
for
"
must substitutable their base
subtypes be

types ?
"

subtype of T objects of typet


→ s is then
a ,

"

may
be
replaced with objects of type
S

Derived substitutable
types be
completely

must

for their base


types .

→ LSP is a
particular definition of a
subtyping
relation , called C. ) behavioral
strong subtyping .

Introduced
by Barbara Leskov

.

→ Extension
of the
Open close principle .

Implementation Guidelines

No
exceptions be
by the
subtype
→ new can thrown .

→ clients should not know which specific subtype


they are
calling .

derived
New classes
just extend without
replacing

the
functionality of old classes .

linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav

ISP Interface Segregation Principle


-

"

Dependency of one class to another should be on

smallest possible interface ?



clients should not be
forced to
implement interface
don't
they use .

fat interface

one need to be
split to
many
smaller and relevant interfaces so that clients can

know about the interfaces that are relevant

to them .


The ISP was first used and
formulated by
Robert for
c. Martin while
consulting Xerox

Case
Study
Problem ? -

had created
printer system that
→ Xerox a new

could perform a
variety of tasks such as

stapling and
faxing along with the
regular
printing task .

→ The
software for this
system was created

from the ground up .


Modifications and
Deployment to the
system
became more
complex .
SOLUTION
→ One
large Job class is
segregated to multiple
interfaces depending on the
requirement .

linkedin.com/in/kapilyadav22
public Animal
Dog
:

Animal
{ feed C);
{ feed :

Pete] ;
pet ; 3
3;

Lion :
public Animal

{ feed C) ;
pete
;✗
3

→ Pet cannot be used for Lion


,
so don't add pet function
in base class .

linkedin.com/in/kapilyadav22
Kapil Yadav

D-
Dependency inversion Principle .

"
(Interfaces)
"

Depend on Abstraction not on concrete classes .

→ level modules should not


depend low-level
High on
-

modules . Both should


depend on abstractions .


Abstractions should not depend on details . Details

should depend on
abstracl.im#- interfaces

interaction level low level


between
high and
NOTE : -
The

should be abstract
modules
thought of as an

interaction between them .

linkedin.com/in/kapilyadav22
Kapil Yadav

OOPS DESIGN PATTERN



formalised Best practices to write clean code .

Creation Factory Abstract Factory Singleton


-

, ,

structural
Bridge Adaptive, Composite
-

,
> Behavioural
Interpreter
_

, strategy ,
observer .

7)
Factory Method
Design Pattern : -

Factory Method design pattern


that define interface abstract class
stays just an or

for let subclass


creating an
object but the decide

which class to instantiate .

→ ( subclasses are
responsible to create the instances
of
the class ?
→ This pattern is also known as Virtual constructor .
Kapil Yadav

→ In above code, if user wants to add Tempo bus Metoo


, ,

info , he/she needs to add it in multiple if else ,

linkedin.com/in/kapilyadav22
Kapil Yadav

our user doesn't want to do it .

→ Now ,
we are
going to create a
factory it will
,

creation
take care
of
entire
logic without
,

it to client/ user, client will not


exposing so

bother .
Kapil Yadav

→ we created the function as static , so that we can

access the function without the


object of class .

will
logic factory if
→ Now , write and
we our in ,

client
any change required ,
will not bothered , we

only need to do
change in
factory .

Library to decide
→ be
should which
responsible obj type
create based
to on
input .

→ client should
just call
library's factory and
pass type
without
worrying
about actual
implementation of creation

of object .

Pattern :
Advantages of Factory Design -

Factory Design Pattern allows the sub-class to choose

the
type of objects to create .

loose
promotes the
couplingclasses
by eliminating the

It -

need to bind
application specific
-
into code the .

Usage of Factory Design Pattern : _


when a class doesn't know what sub-classes will
be required to create .

classes
when class wants that its sub
specify

a -

created
the
objects to be .
Kapil Yadav

Ex-2_: -

Plan
Generate bill
rate
getRate()
calculateBill()

mainC)

extends extends extends asks

Domestic Commercial Institutional GetPlanFactory


Plan Plan Plan
creates

getRate() getRate() getRate()

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

2. SINGLETON DESIGN PATTERN : -

→ New Instance Created . No .

of instances are 1

this
message
is
from user 1 .


New csnstance created .
No .

of instances are 2

this
message is from user 2 .

→ I don't want users to be able to create


my
logger object .


I want to restrict them to able to access

logger constructor .

class
1. Restrict users
from creating object of .


By making the constructor private , we are

oestoicting users
from creating object or

calling the constructor itself .


Kapil Yadav

Kapil Yadav

→ code fails In
Multithreading Case .

Suppose there are two threads


working paralleling
and
they try to create a
logger Instance ,

the first will create a


logger instance because it

is well , same second thread will also do the

same
,
so total 2 instances will be created .

linkedin.com/in/kapilyadav22
Use -
Mute , Kapil Yadav
Kapil Yadav

Our code is now safe on


multithreading but,

we don't need mutex all the time because


,

first time ,
when
logger instance = NOLL
,
and multiple
lock
threads

trying to access
loggesinstanee , we need ,
but

don't lock,
once
loggerinstance is created, we need
double
so
put check
ifcloggerinstance __=nullptD
then lock,
only

use
Kapil Yadav

Double checked
locking
-
: -

check for loggersrstance nullptr


= -

, if we
only
lock null,
need when
loggesirstance check
-_ =
a ,
so

this condition ,
because locks are
expensive .

linkedin.com/in/kapilyadav22
Kapil Yadav

[ ]

linkedin.com/in/kapilyadav22
Kapil Yadav

POINTS TO KEEP IN MIND : -

→ We want to astrict users to access the constructor


but there multiple
are
ways to access the
private
constructor

17 constructor
Make
copy as
private .

27 operator private
Make
equal to ,
overloading as .

From 01-1-11 we also need to use =delel= to


,

astrict to operations
uses
copy .

linkedin.com/in/kapilyadav22
Kapil Yadav

[ T-sxstn.cl
users

linkedin.com/in/kapilyadav22
Kapil Yadav

3 BUILDER DESIGN PATTERN : -

structure
→ whenever we are
building very complex
which has a lot
of configurations in it .

Builder Pattern that


"
construct
complex
says a

object from simple objects using step-by-step approach?


Kapil Yadav

Advantages of Builder
Design Pattern : _

clear
It provides separation between the construction

and
srepzesentation of an
object
.

better control construction


It
provides

over

process .

supports to
change the internal representation of

It

objects .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

4. OBSERVER DESIGN PATTERN : _

"
Pattern
just define
→ observer
An that one-to-one
says
states , all its
dependency so that when one
object changes
dependents are notified and updated automatically .

Ex -

group notifications .

linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav

5. Abstract
Factory Design :


Factory design pattern was
creating concrete classes
or
object .

create
→ Abstract
factory design pattern is
going to

factories that is
going
to coeale
object .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

You might also like