Monday 30 May 2016

References in C++

Nicknames. Who doesn't like a nickname? Those who don't have one. So, who doesn't have a nickname? No one.
Remember how we like to give nice and descriptive names to variables in our programs? I want you to ask yourself a question. If variables have names, can they have nicknames then? And to answer this question (that you asked because I asked you to do so), sure we can have nicknames for variables. 
If you're wondering why is there a need to have nicknames for variables? The answer lies in common sense. Nick names are short names, used as a convenience when calling someone very familiar to you. A computer program can also do the same. We can have a nickname for variables and use these nickname to read/ write and use this variable otherwise.
Speaking technically, in C/C++, a variable (which is nothing but a space in memory) can have multiple names associated with it. One of these names is the actual name, given at the time of declaring the variable. And other names are called references.
A reference to a variable/ object is another name for the same memory address. 
It is kind of like pointing to a variable but with modesty. 

int x=10;

int &y=x; //y is a reference.
//a reference must always be initialized. 
y++; //this will effect the same memory address as of x
cout<<x //11 will be printed.

A reference variable can only refer to one thing and one thing only for ever and ever. This means that if we try to assign some variable to a reference variable after it has been initialized then that only means we are assigning a value to the memory address to which our reference variable referred to.

int x=2, y=5;
int &r=x; //referring to x now and forever.
r=y; /*this does not mean that r refers to y now. It only means that what address r referred to, now contains the value of y.*/
cout<<x; //this will now print 5.

Call by Reference:
I was taught this whole concept of call by reference before I was told that there even existed something called a reference to a variable/ object. I can not begin to tell you how unfair that is. 
If I am being honest, call be reference can be done using pointers alone. But that is like forcing the issue a bit. 
void twice(int *i)
{
      *i= 2*(*i);
}
int main()
{
      int x=10;
      twice(&x); 
      /*after this statement, changes made by twice() will reflect         permanently to x*/
     return 0;
}
The above of course is an example where the changes made by a function are not bound only to the parameters in the function body. They are reflected back to the original arguments as well. This primarily happens because instead of passing a copy of the variable as argument, we pass an address to the functions. And we know how addresses can be so final. 

C++ has a neater way of doing this. This involves the use of references and not pointers. The secret lies in the way in which we define the function:

void twice(int &x)
{
     x=2*x;
}
int main()
{
      int x=10;
      twice(x); /*notice how we don't even need to pass address                            even*/
      return 0;
}

So what happened above? In the function definition, the formal parameter is a reference. A reference which has not yet be initialized (this may sound wrong but it's not). So when we call the function, we pass a variable and not it's address. This variable is then made to be referred by the reference variable in the function definition. And hence the changes made to the reference variable also reflect to the original variable.

The reason why we can have an uninitialized reference variable in a function definition is because variables that are local to a function don't really come into play until they are called. So we can let them be a little spoiled as long as they are not active. And by the time they need to come in action (the function call ), we initialize them immediately (by passing a variable as an argument).

Returning References from Functions:
A function returning a value is like a variable carrying a value. This obviously means that we can use a function (which returns a value) on the right hand side of an expression. 
int func(int x); //assume this function returns some int value.
We can use the above function like so:
int a= func(2);//the value returned by func() directly goes into a
We can even do things like:
int a= 2+3-func(2);

But what if the function returns a reference? In that case we can actually assign something to the value returned by the object. Think of it as this, object returns a nickname of something. We can assign this nickname an actual variable. Basically the function will return a bucket (empty/ full) and we can fill or replace the contents of the bucket.

To understand where this can be used consider the following:
Imagine, a string "govind.sharma". Our job is to replace the dot '.' with a space.
One way to do this would be using a function that returns a reference to the position in the string that contains a dot. And then this reference can be used to assign the value ' ' (space) to the place where the dot was earlier. To do this we can define a function that finds where the dot is and returns a reference to position in the string.

char &dot(string &x) /*The & sign after indicates that this function will be returning a reference to a char. */
{
      for(int i=0; i<x.length(); i++)
      {
            if(x[i]=='.')
            {
                   return x[i]; /*instead of passing the value of x[i], this                                         will return the bucket containing x[i]                                             (for now, we will replace it with a space                                         in a bit)*/
            }
      }
}
int main()
{
      string x;
      x="govind.sharma";
      dot(x)=' '; //change the contents of the bucket
      cout<<x;   //check out the results
      return 0;
}

It is not a given that returning a reference can work only with functions using call by reference (like in this case). It's just what the solution needed. It's not a necessity. 

References to Derived Types:
Similar to the situation as described for pointers in the other post, a base class reference can be used to refer to an object of derived class. The most common application of this is found in function parameters. A base class reference parameter can receive objects of the base class as well as any other type derived from that base.


Restrictions to References:
1) You can not reference another reference. Put differently, you can not obtain the address of a reference.
2) You can not create arrays of references.
3) You can not have a pointer to a reference.
4) You can not reference a bit-field.
5) A reference variable must be initialized when it is declared unless it is a member of a class, a function parameter, or a return value.
6) Null references are prohibited.








Formal and Actual Parameters in C++

Functions are of utmost usage in any language. They are like errand boys for our program. We give them orders and they just take care of things all by them selves. What's so great about functions is the fact that they can be used to do the same thing but on a variety of inputs. This part is called taking orders (or giving, depends on perspective) i.e. doing the same thing/ calculation on different different inputs. These inputs are called parameters. But wait, aren't they called arguments? Well there is indeed a clear distinction between the two (it's minute but clear). Let's get into it then:
I'll say it once and for all, the things that functions take (like orders) and work on them to return stuff are called parameters. But, there are two kinds of parameters:

Formal Parameters:
When we define a function, along with the function signature (it's name) and the return type, we also specify a list of parameters that the function takes. 
type name(parameter list)
This parameter list contains a comma separated list (of course) of variables and their types. These variables are then used inside the function body to write the code and return stuffs as well. 
int add(int x, int y)
These are what we call as formal parameters. Simply put, these are just identifiers that don't have values as of yet but represent what we intend to do with these values if and when we would get them via a function call. 

Actual Parameters:
After a function has been declared and defined it's time to use them. Using a function is exactly like firing orders at an errand boy. And part of the job of calling a function includes giving them some actual values to work with. These values will take the position of formal parameters. Calculations would then proceed based on these values. 
add(2, 3);
These are called actual parameters or arguments. Remember an argument must be a value (not necessarily a literal like 2 or 3). It can either be a straight out value like in the above case or it can be another variable containing some value in turn.
int a, b;
a=2;
b=3;
add(a, b);

Sunday 29 May 2016

The this pointer in C++

The this pointer has a special place in C++. Even though one doesn't get to hear a lot about these, they are always there in a class in C++, always. But before getting into what a this pointer is, let us first start with a normal type of pointer, pointing all so innocently to an object of a class:
class student
{};
student *p;
student obj;
p= &obj;
Now considering our class has a member function: display(). How do we call this function using a pointer? You know how:
p->display();
In the above example, I created a pointer myself, but in C++, an absolutely similar pointer like p is created automatically for every object of every class. That pointer is called the this pointer
The this pointer is local to the object. This means that it can be used meaningfully only inside the object i.e. in the code within the class definition. In order to understand the need for this pointer we have imagine the following scenario:
class A
{
      int x;
public:
      void func(A a)
      {}
}
The member function func() of the above class takes as an argument an object of the type A it self. This is indeed a rather bizarre situation. The function belongs to the class A and hence is defined inside of the class definition. This function is obviously allowed to access all the private, protected and public members of this class. So far so good. Here is how func() may use a member of the class inside it's body:
//assume we are still inside the class definition
void func(A a)
{
      cout<<x;
}
Notice how we use x without any specification to which x this is. This is because x does not require any additional specification at this point. There is only one x in the whole class definition and referring to x could only mean referring to that member. What if I told you that this is a short hand for a more detailed way of referring to x. Indeed there is a more detailed way of referring to a member of a class inside the class definition. This method includes the use of this pointer. This method is used to avoid any ambiguity that may arise over a member of the class. We would look into how such an ambiguity may arise in a bit but first check out how the detailed method works:
//assume we are still inside the class definition
void func(A a)
{
      cout<<this->x;
}
As I told you before, this pointer is nothing but a pointer to the object of the class. And so the syntax of referring to a member of the class using this pointer is the same as doing so using a normal pointer (with the arrow operator). What the cout statement in the above example means is that we wish to print the variable x which is a member of this very object of which this function is a member to. So that x will be printed which belongs to the object through which the function func() was invoked.
A obj1, obj2;
obj1.func(obj2); //will print x belonging to obj1
obj2.func(obj1); //will print x belonging to obj2


The detailed method described above is omitted mostly because it is required only when a foreign object (of the same type) is being used inside the class.

Remember how the this pointer is provided automatically for each object in C++. Well as it happens, the this pointer is also passed to every function of the class as a hidden parameter. You ask why? Well this is because in memory, when objects are created, space is given for only the non static members variables of the object. The member functions for each object are not placed separately in memory along with other things belonging to each object. Member functions are stored only once, with the class definition. And each object of the class uses these solitary definitions of member functions in turn. Then how do the member functions know which object it is this time which is calling them? I mean there doesn't seem to a way for the member functions to differentiate between each calling object unless an argument is passed (secretly) among other arguments to the member function, containing the identity (address) of the object calling for the services of the member function. Hence the this pointer is passed secretly behind our back by the compiler to every member function of the class (only to help us out). This is also the reason why this pointers can be used inside the body of a class definition only (body of the member functions).


Coming back to that ambiguity that I talked about before. When a member function of a class has an object of the same class as it's parameter, then this can lead to a confusion. Confusion on which object's member (the calling object or the parameter object) is being referred to at any point in the function body. When referring to some member (say x) of the calling object, use this->x and when referring to the member of the parameter object use objectName.x.



Such ambiguity can also arise when the member function takes a parameter with a name same to some member of the class. There too, this pointer can be used to save us and the compiler from all of the confusion.

class A
{
      int x;
public:
      void func(int x)
      {
            cout<<x;  //the parameter x
            cout<<this->x; //the member x
      }
}

Well, I have two parting thoughts:

1) Friend functions are not members of a class and therefore are not passed with a this pointer as a secret argument.
2) Static member functions also know nothing about this pointers. This is because static member functions are same for all objects. Objects don't get the luxury of having a personal static member function for themselves. So the whole issue of being able to recognize what object is calling a static member function goes down the drain.

Friday 27 May 2016

I have this super power too.

This one, this particular piece of possibly nonsensical text may prove to be a little extra dimensional. It may take more than a single conscious effort at reading to grasp its entire essence. In fact at the risk of sounding like a bit over confidant, I assure you a definite second read. Read carefully and you’ll know for yourself.
This one is about super powers. To be specific it’s about this single most popular super power in the entire world. But more about that later. First of all I would like to draw out some consequences of having a super power and/or being a super hero. Here goes:

Envy towards those with special abilities is more real than the special ability itself. I mean it’s easier to attract envy then to grow powers that aren’t common. Pretense and pretense alone is enough to make others feel the urge to be less like themselves and more like the one with all the super powers. Don’t mistake this statement for being child centric. It’s very general, crossing boundaries of age, sex, religion and nature. No matter how good you are, you’ll always envy what you are not: our superhero.

A sad implication of being the one with some super power is the fact that you are very unlikely to find and then sustain any friends. Friendship is the cause and a direct consequence of a functional social setting. It is through friends that one enjoys interaction with new people. And it is through these refreshing interactions that one grows more friends. It’s an old social process working in cycles and in most cases reaching a saturation point in the first quarter of life. Obviously the key to all this is the participation and practice of social protocols. That’s something less obvious to people with powers, specially this one power that I’ll come around in a bit.

An even sadder reality is how often the prospect of romance ceases to just dreams and fantasies for this brand of super heroes. Finding love is like losing weight. It demands constant efforts, often involves fighting all your natural instincts and it actually requires you to lose weight. Hence it’s not as simple as a search, it’s as hard as a pursuit. And what’s the most fundamental ability needed for any pursuit? Persistence. Persistence is static. Our super heroes are not. So long story short, our super hero is not someone to be jealous of after all.

Social alienation, public disapproval and loneliness at personal levels are only some of the perks of being the possessor of this particular super power. In a nutshell, having this super power forces you to be different. Different from normal, fringing near lunacy, being eccentric. In fact, being awkwardly different is the super power I had in mind throughout. Read again (starting with the title), this time bearing this new and rather sober revelation in mind and I hope you’ll see how this whole article fits so perfectly for a weirdo.