Wednesday 17 February 2016

Constructor and problem of initialization in C++


  • Constructor is a member function of a class.
  • The name of constructor is same as the name of the class.
  • It has no return type, so the definition of constructor can not use the return keyword.
  • Normally, if we don't write return type of any function then by default its return type is considered as int.
  • But in case of constructor it has no return type.
  • It must be an instance member function, that is it can never be qualified with static keyword.

How to call constructor?
  • Constructor is implicitly invoked when as object is created.
  • Constructor is used to solve problem of initialization.
What is problem of initialization?
Okay, the answer to this question is the answer to the question " why is it called constructor? "
A constructor makes an object an object., this may sound crazy but yes this is true. As in our normal life we say "become a human" ( i.e. become a good person with good characteristics ). Similarly, the constructor makes an object as a good object.
Consider an example:
class
{
  private:
  int car_number;
  string color;
......
};
Now if we create an object to the class, then the instance member variables will have some garbage values into them and thus we can not point to a particular car. If we would have used a constructor to initialize the car_number and colour, then we can point to a particular car. Thus a constructor makes object as a perfect object. 
So we need to initialize the instance member variable at the time of creation of objects and that can be done by using the constructors.

Important topics in constructor:
  • Default constructor
  • Parametrized Constructor
  • Constructor overloading
  • Copy constructor.

Question on static member variable in C++

Question: What is the output of the program written below ?

#include<iostream>
class Account
{
  private:
    int balance;
    static float roi;
  public:
    void setBalance(int b)
    {
      balance = b;
    }
    void showBalance()
    {
      std::cout<<"Balance is : "<<balance<<std::endl;
    }
    static void setRoi(double r)
    {
      roi = r;
    }
    static void showRoi()
    {
      std::cout<<"Roi is : "<<roi<<std::endl;
    }
};
float Account:: roi;
int main()
{
  Account:: setRoi(3.6f);
  Account:: showRoi();
  Account obj;
  obj.setBalance(9999999);
  obj.showBalance();
  std::cout<<"Size of the Account object is : "<<sizeof obj<<std::endl;
  return 0;
}

Answer :
Roi is : 3.6
Balance is : 9999999
Size of the Account object is : 4

Reason :
The static member variable does not belong to the instance of class(i.e it does not belong to the object of the class). So, the object 'obj' has only on variable contained into it, which is 'balance'. And thus the size of the object 'obj' is 4 (size of an integer),

NOTE: this output is in context with the compiler GCC 5.1

Static member function in C++

Okay, before I start the main portion of the static member function, I would like you to know that a instance (normal) function can assess both the instance member variable as well as the static member variable. So, the question the arise is that "Why do we need static member function?"

Reason for static member function :
If we want to access the private static member variable then we need a member function. Now as we know that static member variable is class member variable i.e it will occupy memory in RAM even if the object of class is not created and if we make a instance(normal) member function then we need a object to call it. Thus the significance of the static member variable will be lost because anyway we are creating an object to access the static member variable. So we need to qualify the member function with static keyword to make it static member function. And now this member function can be accessed without any object of the class.

Example :

static void setValue(float sal)
{
    salary = sal;
}

Special things about static member functions:

  • They can access only static member variables because these functions can be called without any object.
  • If object is present then we can call it in two ways:

    a1.setValue(9999999.5f); // a1 is the object of class people
    people:: setValue(999999.5f);


  • If object is not present then we need to use the second method to call the static member function.


NOTE:
The instance member function can access both the static member variable and the instance member variable.
The static member function can be called with or without objects.

Static member function in C++

There are two types of member variables in a class in C++.

  • Instance member variable - belongs to the instance(object) of the class.
  • Static member variable - belongs to the whole class.


Here we will study about the static member variable.
Key points:

  • Declared (but not initialized) inside the class body.
  • Also known as the class member variable.
  • They must be defined (or initialized) outside the class.
  • Static member variable does not belong to any particular object, but to the whole of the class.
  • There will be only one copy of static member variable.
  • Any object can use the same copy of static member variable or the class variable.


Explanation :
Meaning of static member variable is " declaration of a variable qualified with static keyword into a class".
Example:

class people
{
  private:
    int a;
    static float salary;
  public:
    void setSalary(int b)
    { a = b; }
};

Now in main if we make an object of the class people like.
void main()
{
  people a1;
}

'a1' is an object in which there will be only one variable 'a' and 'salary' variable is not a part of the object a1.
Even is I don't make any object to the class then also othe 'salary' variable exists.

Important Notes:

  • In C++ if we just declare the static variable into the class then that variable does not get any memory.
  • We need to write the defination of the static member variable then only static variable will get memory.
  • The definition of static member variable has to be written outside the class.
  • eg. of definition is :- float people:: salary = 9999999.5f;
  • If we want to use the static member variable in any other functio then we can use it with help of membership label (class name and scope resolution)
  • It we want to use the static member variable through an object then also we can use it normally as we use other instance member variable of class. But same memory will be used for all the objects.
  • Note that if static member variable is private then we can not access it directly outside the class and thus to access this we need to make a member function which has to be a static member function.


For more details visit here.

Static local variables in C++

The concept of static local variable was present in C programming language. But in C++ we have two new concepts related to static keyword. In C++ we have concept of static member variable and static member function. But here in this post I will tell you about the static local variable.

Key points:

  • Concept as is taken from C.
  • They are by default initialized to zero..
  • Their lifetime is through out the program.
  • But their scope is limited to that block only where it is declared.
  • Meaning of static local variable is " declaration of a variable qualified with static keyword into a block/function of program.
  • Example:

void fun()
{
    int y;
    static int x; // static local variable
}

Things that should always be kept in mind about static variable is :

  • Its by default value is 0.
  • Its lifetime is throughout the program.
  • In the above function variable 'y' is not static and thus the variable 'y' will get memory only when fun() is called. But variable 'x' gets the memory at the time of start of the program.
  • Although its lifetime is throughout the program , but its scope is limited to the block where it is declared.


For more information you can visit here.

Monday 8 February 2016

Reference Variables in C++

We have seen types of variables while studying C and C++ and we know that In C++ we have 3 different types of variables:
  • Ordinary Variable // int x;
  • Pointer Variable   // int *x;
  • Reference Variable  // int &y = x;
Here we are going to study about the reference variable and how it is different from other types of variables and why do we need the reference variables when we already have pointers?.

Okay, First have a look at the syntax of reference variable :
int &y = x;
  • Here the symbol '&' will not be called as the 'address of' operator.
  • It will be called reference operator.
  • We would have called '&' as the address of operator, if the '&' will be at right side of ' = ' (assignment operator).
Some time I also call the reference variable as the internal pointer because it works exactly (not all time) the same as the pointer variable.

Some Important points:

  • It is important to initialize the reference variable while its declaration.
  • And the initialization should be done with a variable which is already present in the memory of program.
  • eg.
  • if we write this :
  • int &y = x;
  • Then 'x' has to be already declared into the program (i.e  there has to be a memory allocated for x)
  • 'y' is just another name of x.
  • For understanding purpose we can say that there are two name of same block in the memory of the program. (Note that this statement is illusion,  the truth is that u is also a seperate variable which has the reference of x [i.e address of x])
  • Reference variable is initialized with already declared variables only.
  • Reference variables can't be updated.
Why do we need reference variable?
Answer : We use the reference variable for operator overloading. Except operator overloading there are no task which can't be accomplished with pointers. Even sometime operator overloading will also not have any problem with pointer variables as the parameters. But there are cases when using pointers for "passing via reference" would give you unacceptable syntax.
There is a link here. Here you will find a answer given by Strousturup about the inclusion of reference variable in C++ program.
For more programming knowledge you can visit here.

Sunday 7 February 2016

Record Screen with audio in Linux using shell script | Very Easy

Here is a video which will help you to record your screen on Linux:



This is really a best method to record screen with audio on Linux and this is also very easy to do.
You can do it in  few minutes.

Saturday 6 February 2016

How to Record Desktop Screen in HD using VLC.

This is a video you can follow to record desktop screen in HD.





This Video contains few steps that you need to do to record the desktop and you can also find those steps in the description of this video on YouTube.

Friday 5 February 2016

Simplest way to learn Bubble Sort

On this link I told you the simplest way to learn selection sort. But selection sort is not the best preferred sorting method.
Selection sort is little slower than the bubble sort.
Suppose we have an array : 2, 7, 4, 1, 5, 3
Key Point to Note:
  • Here we are going to scan each element of the array from left to right multiple times.
  • The reason for scanning the array multiple times is that when we are at some perticular element then we will compare that element with its next adjecent element. (i.e if we are at 0 index, then we will compare that element with the element at index 1.)
  • And if the element at the current position is greater than the element at next position then we will swap these two elements. (if in case we are at index 1, then swapping will take place between ARRAY[1] and ARRAY[2]).
  • Similarly after one complete scan of the array we will get a new array which will be: 2,4,1,5,3,7
  • Clearly, we can note that the element which is largest in the array is not present at the last index of the array.

Why we call this at bubble sort?
We can clearly notice that the largest element has kind of bubbled up to the last index in the array. So this sorting method is known at the bubble sort.

Sudo code for one pass:

for ( i = 0 to size-2 )
    if Array[i] > Array[i+1]
        swap( Array[i] , Array[i+1] )


  • Now after the second pass the array will be : 2, 1, 4, 3, 5, 7  
  • Similarly we need to have such "size-1" passes.

Reason for "size-1" passes:
we need only size-1 passes because if we have sorted the size-1 elements then the last element left will already be sorted.
  • So now we need to have another loop to control the number of passes required. So we need to write two loops.
  • One Loop will count the number of passes(outer loop) and the other loop will be used to swap the elements of array if required(inner loop)

So now we can write the code of bubble sort.

Bubble Sort in Ascending order:
#include<iostream>
void swap(int Array[], int index)
{
    int temp = Array[index];
    Array[index] = Array[index+1];
    Array[index+1] = temp;
}
void bubbleSort(int Array[], int size)
{
    int flag = 0;
    for(int i = 0; i < size-1 && flag == 0; i++)
    {
        for(int j = 0; j < size-i-1; j++ )
        {
            if(Array[j] > Array[j+1])
            {
                 swap(Array, j);
                 flag = 1;
            }
        }
        if(flag == 0)   //no swapping haapen so break the loop
            break;
        flag = 0;
    }
}
int main()
{
    int size, Array[50];
    std::cout<<"\n Enter the number of elements in the array : ";
    std::cin>>size;
    std::cout<<"\n Enter the elements of the array : \n";
    for(int i = 0; i < size; i++)
        std::cin>>Array[i];
    bubbleSort(Array, size);
    std::cout<<"\n The array after soring is : \n";
    for(int i = 0; i < size; i++)
        std::cout<<" "<<Array[i];
    return 0;
}

Wednesday 3 February 2016

How to use character array as strings in C++ program.

There are many different ways in which we can use strings in our C++ program and today we will find the best way to use a string in your program.
For now we will have look on the different ways of using String.
First way:
Since C++ is a super-set of C, so we can use the strings in the same style we used it C language. In C we say that :
string = array of characters.
So whenever we need to use a string we just make a array of characters.
EXAMPLE:
char str[50];  -> Here 'str' is an array of 50 characters
As we know that array is nothing be contiguous block of memory. So here we have 50 contiguous block of memory.
Since we are now in 2016 and thus using character buffer for string would be a very bad idea. Plus this is not memory efficient.
When we write char str[50] then the program will occupy 50 bytes of memory no matter whatever we store into it. So this is something we would never want to do. However this is just a brief description of why we should not use the character array in our normal practice.
Now I will tell you "how to accept strings from user?"
To accept string using the character array we just can't use the cin( or std::cin ) because this just stops reading when it will encounter a space. It sees a lexical token as a "string".
We can use cin.getline() :
char str[50];
cin.getline(str, sizeof(str));
instead of sizeof(str) we could have also used 50. see below:
char str[50];
cin.getline(str, 50);
Former is better than later.
REASON:
I would use sizeof(input) in place of 50 in the call to cin.getline(); because it would mean we can change the size of the input buffer and only need to change one line instead of two lines.

SIZE of str:
sizeof(str);
The size will always be 50 bytes.

TYPE of str:
typeid(str).name(); // comes under #include<typeinfo>
The type will be "Array of 50 characters".

Next I will tell you a good and efficient way to use strings in C++.
Thanks

Tuesday 2 February 2016

Simplest way to understand Selection Sort

Suppose the we have set of cards, now we keep all the cards in our left hand and select one smallest card and then transfer that card to our right hand, similarly we repeat the process with all other cards then we will get all sorted cards in our right hand.

Below is pictorial representation of the example.
This is the set of cards that we have kept in our left hand.
Now we are transferring the smallest cards from our left hand to right hand one by one.

And thus now we come up with a sorted bunch of cards in our right hand.

You can apply this same approach in the programming. You have to notice thing that in the above example of "sorting of cards" we have used our two hands but in case of programming we have to use only one array.
We will see how we can use only a single array.
Now suppose that we have an array :
3,7,5,1,4,2
Now one way of sorting this can be selecting the smallest element from the array and strong it into another empty array and continuing the same procedure again and again. (But this will occupy extra memory space) So we will not follow this method.
Second approach:
We will look at the index of smallest element, and then we can swap that element with element of zero index. And again we can search of the minimum element and swap it with the element at index `1`. Repeat the same procedure and you will end up with a sorted array.

Algorithm of Selection Sort:

SelectinSort(Array, Size)
    for i <- 0 to n-2
        min = i
        for j = i+1 to n-1
            if Array[j] < Array[min]
                min = j
    swap Array[i] and Array[min]
Done
Program of Selection Sort:
This sorting is in ascending order.
#include<iostream>
void SelectionSort(int Array[], int size)
{
    int min, flag = 0; // flag is taken to check if the value of min changes or not
    for(int i = 0; i < size-2; i++)
    {
        min = i;
        for(int j = i+1; j < size-1; j++)
        {
            if(Array[j]<Array[min])
            {
                min = j;
                flag = 1;
            }
        }
        if(flag = 1)
        {
            int temp = Array[i];
            Array[i] = Array[min];
            Array[min] = temp;
        }
    }
    return;
}
int main()
{
    int Array[100];
    int Size;
    std::cout<<"\n Enter the number of elements you want to sort : ";
    std::cin>>Size;
    std::cout<<"\n Enter the elements of array : \n";
    for(int i = 0 ; i < Size; i++)
        std::cin>>Array[i];
    std::cout<<"\n Array before sorting is : \n";
    for(int i = 0 ; i < Size; i++)
        std::cout<<" "<<Array[i];
    SelectionSort(Array, Size);
    std::cout<<"\n The array after sorting is : \n";
    for(int i = 0 ; i < Size; i++)
        std::cout<<" "<<Array[i];
    return 0;
}

If you have any doubt then just comment below or send an email of youarefreak1@gmail.com.
Thanks.

Han Solo and Lazer Gun Solution | Codeforces Problem Solved

The full problem statement is here.

Solution to this problem is :

#include <bits/stdc++.h>
using namespace std;

struct point {
    int x, y;
    point (int x, int y) : x(x), y(y) {}
    point () {}
    void in () {
        cin >> x >> y;
    }
    bool operator < (point p) const {
        if(x == p.x) return (y < p.y);
        return x < p.x;
    }
};
map <point, int> f;

int pos(int x) {
    return (x < 0) ? -x : x;
}
point normal(int x, int y) {
    if(y < 0) {
        x *= -1;
        y *= -1;
    }
    if(y == 0) {
        if(x < 0) x *= -1;
    }
    int d = __gcd(pos(x), pos(y));
    return point(x / d, y / d);
}

int main()
{
    ios_base :: sync_with_stdio (0);
    cin.tie(0);

    int n;
    cin >> n;

    point o;
    o.in();

    int ans = 0;
    for(int i = 1; i <= n; i++) {
        point p;
        p.in();
        p = normal(p.x - o.x, p.y - o.y);

        if(f[p] == 0) {
            ans += 1;
            f[p] = 1;
        }
    }
    cout << ans << endl;
    return 0;
}

How to know the type of en expression at run-time of a C++ program?

Most of us know that how to get the type of variable in C++ at compile time.
Example:
#include<iostream>
#include<typeinfo>
int main()
{
    int var = 10;
    std::cout<<"\n The type of the variable var is "<<typeid(var).name()<<std::endl;
    return 0;
}

Output:
The type of the variable var is i
i represents integer.

Now suppose we have a program like this :
#include<iostream>
#include<typeinfo>
int main()
{
    int var;
    std::cin>>var;
    std::cout<<typeid(5.0/var).name()<<std::endl;
    return 0;
}
Now suppose that you give the input as 5. Then you might except the output to be i. But this will not happen and the output for any input here will be d (d for decimal).

Okay then what is the reason behind this?
The answer is that typeid only tells you about the static type determined at compile-time. The expression we have written is always floating-point.

To know that what is the type of the expression we don't have any predefined function in C++ however this can be done easily in programming language like python, ruby.
To know the type whether the expression is decimal or integer we can evaluate the expression and store it into a float type variable. And again you store the same evaluated expression into an integer type variable. Now if you subtract the integer type variable with the floating type variable you will get the decimal value.
If that subtracted value is 0 then we can easily say that the expression has integer value otherwise it must be a float.

So the above program can be written like.
#include<iostream>
#include<typeinfo>
int main()
{
    int var;
    std::cin>>var;
    int a = 5.0/var;
    float b = 5.0/var;
    if(b-a == 0)
        std::cout<<"\n integer";
    else
        std::cout<<"\n decimal";
    return 0;
}
Now this will be a perfect way to know the type of the expression at run-time of a program. Well there are many more methods you can think of.