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.