Wednesday, 24 June 2020

Polymorphism

Polymorphism

Polymorphism meaning having many forms.
In C++ there are two types of polymorphism
  • Compile-time polymorphism
  • Run-Time polymorphism


Compile time polymorphism 

The binding happens at compile time, meaning based on the arguments the compiler tries to interpret the function call.
It can be observed with function overloading. Based on the type of arguments passed, the compiler decides which function to call. 

Run time polymorphism 

The binding happens at run time. Function over-riding is an example of Run-time polymorphism.
Here is a simple example of Run-time polymorphism.

In the above example, based on the type of the object the pointer is holding we would want the function to be called. If it is Dog pointer, then the Dog class's sound method is executed. This feature of the compiler to identify the type of object at run time and call the correct method is called Run time polymorphism. For this to occur the base class should have atleast one virtual function.


Saturday, 20 June 2020

Casting

Implicit casting:
when we assign a float to integer, compiler implicitly casts it

Explicit casting.
We tell the compiler that I want this type to cast to another type, and we are aware of data loss that might occur.

const_cast
Used to cast away constness of a variable.
We can change non-const class member inside const member function.
We can pass const data to a function that wont take constant.
Undefined behaviour on modifying variable declared as const
It is safer

static_cast
Casting a float to int using static_cast.
It is compile-time cast
It performs a strict type checking.
Cannot cast incompatible types
Gives compilation error if matching types not casted

dynamic_cast
Can be used only with pointers and references to objects.
Always successful from derived to base
Base to derived is not allowed unless for polymorphic
dynamic_cast checks RTTI to return the complete valid object
Returns nullpointer in case it is not able to return the valid object
Throws bad_cast exception in case of reference.
Can cast void pointer to any class (even unrelated)
Can cast any type of pointer to void pointers

reinterpret_cast
Converts any type of pointer to any other type (whether related or not)

Tuesday, 16 June 2020

InsertionSort


Insertion sort is similar to sorting playing cards.
Start with second element and keep in correct location to its left.
Only difference in programming is all the other elements need to be moved to the right to make place for the incoming element.
It is particularly useful for partially sorted array.



Time complexity : O(n2)
Extra Memory:θ(1)
Stable : Yes



Monday, 15 June 2020

Singleton Design Pattern

In singleton design pattern, we restrict the instantiation of the object to only one. We make the constructor private and create a static method to control the instantiation