Constructors in C++

A constructor, as its name implies, is used to create (construct) objects. It's like any another function but with exceptions -
A constructor is always associated with a class and this function does not return anything and thus it does not have any return type associated with it.
It is used only for aiding in creation of objects. Let's look at how a normal function looks:

// this function has a return type of 'int'
int add(int a, int b) {
 return a + b;
}

Name of the function is add, its return type is int (i.e it returns an integer after it is done with its operations) and it takes in two parameters - a and b.
Now, let's say we have a Box class and for creating a Box we need to follow some steps, we cannot just create one out of nothing. For example, we cannot create a Box without the required width and height obviously! Here's how a constructor for the Box class might look like:

class Box {
public:
 // Box is the name of the constructor function
 // ITS NAME IS ALWAYS THE SAME AS ITS CLASS NAME
 // Since, a constructor function does not return anything,
 // it does not have a return type before its name
 Box(int width, int height) {
  // this constructor takes width and height

  /*
  Possible steps to make a Box object

  1.  Get a cardboard
  2.  Get the desired width and height
  3.  Make (construct) the box by
   cutting the cardboard according to width/height
  */
 }
};

Here, we defined a constructor for the Box class. Notice, the name of the constructor function is the same its class name and that it has no return type. Let's complete the definition of our class and use it in code.

#include <iostream>
using namespace std;

class Box {
 int box_width;
 int box_height;

public:
 // Box is the name of the constructor function
 // ITS NAME IS ALWAYS THE SAME AS ITS CLASS NAME
 // Since, a constructor function does not return anything,
 // it does not have a return type before its name
 Box(int width, int height) {
  // this constructor takes width and height

  /*
  Possible steps to make a Box object

  1.  Get a cardboard
  2.  Get the desired width and height
  3.  Make (construct) the box by
   cutting the cardboard according to width/height
  */

  box_width = width;
  box_height = height;

  cout << "Making a new box..." << endl;
  cout << "Gathering some cardboard..." << endl;
  cout << "Width: " << box_width << endl << "Height: " << box_height << endl;
  cout << "Making the box with the given width and height..." << endl;
  cout << "Done! Enjoy your new box" << endl;
 }
};

int main() {
 // Create a Box object named b
 Box b(30, 20);

 return 0;
}

Now, run this program yourself and enjoy making new boxes!

Classes and Objects in C++ and real life

Class. Object. They are used frequently in the land of object oriented programming (OOP). Classes and objects are nothing mysterious. Look around you, there are so many objects - table, chair, mobile, TV, fridge, etc. All of these are real life objects.

Manufacturers use blueprints to create these objects. The blueprints define how every object of a particular type of product (say iPhone 7) will look like and how they'll behave. Since, all the iPhone 7 objects are created from a single iPhone 7 blueprint, they all look and behave the same, for example - they all have a camera at the back, they can make calls, etc. In our OOP land, these blueprints are known as Class. A class defines how an object will be created, the properties it'll have and the actions that can be performed on that object.

Now let's observe an object. Each object has its own properties, for example, think of your mobile phone - it has properties like "the phone is switched on/off", "the phone's brightness level is set to 5", "the phone is in vibration mode" and so on. Apart from the properties that your mobile has, you can also do stuffs (perform some action) with it - "switch on/off the phone", "increase brightness level", "make a call", "text to someone", etc. This is exactly what an object in OOP is. An object has properties and functions/methods (which perform an action).

Now that we know what an object and a class is, let's see how they're defined in code by creating a Mobile class:

#include <iostream>
using namespace std;

class Mobile {
 // name of the mobile
 string mobile_name;
 // volume level of the mobile
 int volume_level;
 // brightness level of the mobile
 int brightness_level;
 // by default the phone is off
 bool phone_is_on = false;
};

We defined a Mobile blueprint (class) which has properties - mobile_name, volume_level, brightness_level and phone_is_on (which denotes the phone is either on/off). Now, let's define some actions for the Mobile class.

class Mobile {
 // name of the mobile
 string mobile_name;
 // volume level of the mobile
 int volume_level;
 // brightness level of the mobile
 int brightness_level;
 // by default the phone is off
 bool phone_is_on = false;

public:
 void toggle_phone_state() {
  if (phone_is_on == false) {
   cout << "Phone is switched on." << endl;
   phone_is_on = true;
  } else {
   cout << "Phone is switched off." << endl;
   phone_is_on = false;
  }
 }

 void set_volume(int vol) {
  volume_level = vol;
 }

 void set_brightness(int brightness) {
  brightness_level = brightness;
 }
};

Now, we have defined actions for the class. Notice, how actions (methods/member functions) are just plain ordinary functions. Let's use this blueprint (class) to create an object.

#include <iostream>
using namespace std;

class Mobile {
 // name of the mobile
 string mobile_name;
 // volume level of the mobile
 int volume_level;
 // brightness level of the mobile
 int brightness_level;
 // by default the phone is off
 bool phone_is_on = false;

public:
 void toggle_phone_state() {
  if (phone_is_on == false) {
   cout << "Phone is switched on." << endl;
   phone_is_on = true;
  } else {
   cout << "Phone is switched off." << endl;
   phone_is_on = false;
  }
 }

 void set_volume(int vol) {
  cout << "New volume is: " << vol << endl;
  volume_level = vol;
 }

 void set_brightness(int brightness) {
  cout << "New brightness is: " << brightness << endl;
  brightness_level = brightness;
 }
};

int main() {
 // Create an object of class Mobile named - my_android
 Mobile my_android;
 // perform actions on the my_android object by using a dot and the action name
 // my_android . action_name();
 my_android.toggle_phone_state();
 my_android.set_volume(5);
 my_android.set_brightness(3);

 return 0;
}

NOTE: You may have noticed a public keyword. Its okay to not understand it for now, just write it as it is.
Now, you can create as many Mobiles as you want. Go and run the program!

Function overloading in C++: Basic

Function overloading is an interesting concept and its very useful in some scenarios. So, what is function overloading? Function overloading means defining multiple functions with the same name which differ in either their parameter numbers, parameter types or both. Let's see an example to clear things out:
Let's say we want to define an add function. Depending on the type of its parameters, it'll return different values. For example, when you pass two integers 5 and 3 it'll return 8. When you pass 5.05 and 2.90 it'll return 7.95, when you pass two strings - "hello " and "world" it'll concatenate (join) them together and return "hello world". Here's how we do can do it -

#include <iostream>
using namespace std;

// add two 'int' and return their sum
int add(int a, int b) {
 return a + b;
}

// add two 'double' and return their sum
double add(double a, double b) {
 return a + b;
}

// concatenate (join) two 'string' and return the result
string add(string a, string b) {
 return a + b;
}

// this function just adds 5 to any number it is supplied
int add(int x) {
 return x + 5;
}

int main() {
 // this add(5, 3) will call the function at line 5
 cout << add(5, 3) << endl;

 // this add(5.05, 2.90) will call the function at line 10
 cout << add(5.05, 2.90) << endl;

 // this add("hello ", "world") will call the function at line 15
 cout << add("hello ", "world") << endl;

 // this add(10) will call the funciton at line 20
 cout << add(10) << endl;number

 return 0;
}

The output will be:

8
7.95
hello world
15

As you can see, depending on the type and/or number of arguments supplied, the compiler is smart enough to call the correct function.
Function overloading is also possible in the context of a class. You can have multiple overloaded functions as members of the same class. Not only that, even constructors can be overridden.

NOTE: Return type of a function is never taken into consideration in case of function overloading. Always keep that in mind.

Default parameters in C++

In C++, you can define a default value for parameter(s) of a function. Here's how you do it:

#include <iostream>
using namespace std;

void show_info(string name = "Pantha", int age = 20) {
 cout << name << " is " << age << " years old." << endl;
}

int main() {
 show_info();
 show_info("Beck");
 show_info("Tony", 22);

 return 0;
}

Here, we have defined a function named show_info which takes two arguments - name and age. We also set a default value for name = "Pantha" (which is of type string) and also, the default value for age = 20. Then we call the function show_info three times - three different ways (in this case). Its as easy as that!
One more thing that you should be aware of is, you cannot change the position of arguments while calling the function. For example, you CANNOT DO the following:

show_info(20, "Andy");

That's all!

C++ vector basics

What is a container (in our day to day life)? A container is something that holds some stuffs. In that sense, arrays that we declare in C++ can also be called containers. They hold some values together under one name (the name of the array). Here's how we define an array of ints:

int x[3] = {10, 30, 5};

(You can define an array in other ways too, but let's not get into that here). This array, which is named x, is an array of 3 integers. Now, what if we wanted to add another integer, say 500, to this array, how would we do so? Maybe you're thinking of creating another array with size 4 and copying all the previous values into the new array including the new value we just wanted to put. Or even better, instead of increasing the size to 4, double the size of the new array so that we don't have to resize it frequently. But all this boilerplate code for just a simple operation! What if there was a data structure (a container) which would automatically increase its size as we put items into it and shrink itself as we purge items from it? Welcome std::vector (resides in the <vector> header)! vector is a container which is very similar to an array, in simpler terms, you can think of vectors as an array and you can almost always use it in place of an array. Its a very convenient data type which is provided by the Standard Template Library (STL) in the std namespace. So, let's see how we can define a vector and use it.

#include <iostream>
#include <vector>
using namespace std;

int main() {
 // this is our plain old array
 int x[3] = {10, 30, 5};

 // and this is our new vector!
 // this statement is equivalent to saying,
 // I want a vector named 'v' which will hold 'int' values
 vector<int> v;

 // now, lets insert values into the vector v
 v.push_back(10);
 v.push_back(30);
 v.push_back(5);

 // See? We did not specify the size of the vector
 // while declaring, it automatically grew in size
 // to accommodate for the new values

 // now, we can iterate over the vector just like an array!
 // NOTE: We can get the size of a vector very easily
 // by calling its size() method
 for (int i = 0; i < v.size(); i++) {
  cout << v[i] << endl;
 }

 // EXTRA! When you use a vector, you can use another
 // version of for loop known as for-each, which is available
 // in C++11 and up
 for (int i : v) {
  cout << i << endl;
 }

 return 0;
}

That's it for the basics!

Tip: Downloading files faster (for slow downloads)

If your internet connection has a good speed but one of your downloads is taking too much time, then its happening most probably because of server location. To download such files faster, try using a free proxy site such as https://hide.me/en/proxy for downloading the file. If your download is still slow, try selecting a different location for your proxy browsing. 

Learning Django - 2

This is the second post among a series of posts about my django learning experience.

I'll start clean and set things up for the whole development process. I'll be using, Ubuntu, Python 3 (https://www.python.org/downloads), virtualenv (https://virtualenv.pypa.io) so that I don't have any dependency conflicts with my other projects, pip for installing these tools and obviously django. Considering that I have the latest python 3 installed (pip comes packaged by default), I ran the following command ($ denotes a terminal session):

$ # Use the sudo command if necessary (only applicable for *nix systems, n/a for windows)
$ [sudo] pip install virtualenv
$ virtualenv virtual_folder
$ cd virtual_folder
$ source bin/activate

This installed virtualenv (short for Virtual Environment) and created a directory named virtual_folder for holding the new virtual environment. cd-ed into it and activated the virtual environment. Deactivating is easy, just run deactivate and it'll deactivate itself. Next, I'll install django with this command:

$ [sudo] pip install django

After django is installed, a terminal restart was needed to load in the new binary. Then I created a project named website with this:

$ django-admin startproject website

A new directory named website is created in the current directory. This contains all the necessary backbone for running a simple django server. cd (change the terminal's directory to point to it) into it. Now, the initial configuration is done and its time for a test run! Run this command:

$ python manage.py runserver

And it should start a server in the localhost at port 8000 or whichever is printed in your terminal. Visit: http://127.0.0.1:8000/ to view the new django server up and running! I'll be explaining in short, what each file is and why its necessary in my next post.

This is it for the initial setups.

Learning Django - 1

I'll be writing a series of posts as I continue my journey to learning django from scratch (note, I already know to some extent and use django but I felt like I had a gap somewhere in the middle). So, this is the first post of the a series of posts I'm going to write about django as I continue my journey learning it!

First, what is Django anyway? Django is a web (application) development framework for the Python programming language. It's available at https://www.djangoproject.com
As of writing this, the latest available version is 1.11.3 which I'll be using over the course of my learning path. Some of the prominent features of django include security right from the start, scalability (Instagram runs on Django, although there are other technologies in their stack for managing different parts of the whole infrastructure), built in ORM for database access, built in template system, etc. Django's philosophy towards development is the MVC (Model View Controller) pattern as described here in detail: https://docs.djangoproject.com/en/1.11/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names

That's all for the first post!

Power function

In C/C++ (and also other languages), we have the built in power function to raise a number to a given power. What if we need to calculate ...