Thursday, March 17, 2016

Constructors in C++

Constructors in C++ 


Dear Folks.. 
A constructor is a method/member function
which constructs an object. Since an object is user defined variable, there must be some special way to allocate memory for it. This task of allocating, required amount of memory for an object and setting-up it's initial values, is done by this special method/member function.

It is special, as it has method name as class-name for which it is being defined.
The basic characteristics of a constructor are...
  • method name same as class-name
  • has no return type, not even as void
  • called automatically when an object is created
  • usually defined with public scope
  • can not be defined as virtual for polymorphism
Types of constructors: Broadly we find three types of constructors namely
  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
Default Constructor: It is responsible for allocating memory for an object which has no parameters. It is characterizied with no arguments in the definition.
If the class has not defined any constructor for it's objects, then the compiler supplies this constructor, hence the name default. Bear in mind, if you define some type of constructor, without defining default constructor, assuming that, the compiler supplies it, this will not work, if you are creating an object without args,some where in the program.In this case, the default constructor must be defined by you.

Parameterized constructor: It is used to create and initialize objects with arguments. Usually it is used to initialize instance variables.

Copy constructor: It is used to copy states of one object into another object which is being created. It performs deep copy(makes a copy of every state).

// An example to demonstrate all these constructors.
class Account
{
  private:   int acc_no;
             double balance;
  public: /* default constructor*/
          Account(){ acc_no = 100; balance = 500;}
          /* parameterized constructor*/
          Account(int n, double x)
          {
            acc_no = n;
            balance=x;
          }
          /* copy constructor*/
          Account(Account & ax)
          {
            ax.acc_no = acc_no;
            ax.balance =  balance;
          }
          void show()
          {
           cout<<" Account No:"<<acc_no<<endl;
           cout<<" Balance :"<<balance<<endl;
          }
};

void main()
{
  Account a1,a2(121,5000),a3(131,7000);
  Account a4(a2);
  a1.show();
  a2.show();
  a3.show();
  a4.show();
}

output:
Account No:100
Balance :500

Account No:121
Balance :5000

Account No:131
Balance :7000

Account No:121
Balance :5000

If find it useful please share it...

Tuesday, March 15, 2016

What is garbage collection in Java

Dear Folks !
This post has a very interesting topic for discussion, i.e Garbage collection in Java...

We know memory management is a crucial aspect in programming. In programming languages like C/C++, programmer can allocate and de-allocate memory at run-time of the program. 

Perhaps, you are aware, memory for local variable, is cleared by the system automatically, once the variable goes out of scope.(i.e when control exits the block{} in which it is created).But, when memory  is allocated at run-time from Heap section, it must be de-allocated by the programmer itself.

We programmers are human beings, obviously have the tendency of forgetting things. So what happens if we forget to free/de-allocate the memory which we have allocated at run-time, somewhere in the program. This image makes it clear.


Did you get the point ? 
Yes ! You are right ! When the same program is run multiple times, every time memory is allocated but not made free, so this makes the memory full and make it crash !

How good it is ! if some one manages this de-allocation task from our side...
Be happy ! Garbage Collector is there for you ! Let's see how it does !

Garbage collector is program(thread),running in the background, to find or locate unreachable objects in heap. An object is said be unreachable if it has no reference in stack to refer it. So any object which is no more referenced, is claimed back by the garbage collector. Thus making the memory free for reuse.
Before,claiming the memory back, the garbage collector calls finalize() method to relinquish any resource held by the object(like file,socket etc).

Let me demonstrate it with this example...
class A
{ --------- }

class DemoGC
{
 public static void main(String arg[])
{
 A a1 = new A();
 A a2 = new A();
 A a3 = new A();
-----
----- 
A a4,a5,a6;
a4 = new A();
a5 = new A();
a6 = new A();
-----
-----
a1 = a4; 
/* here the address of a4 overwrites address of a1-- This is how, a1 becomes unreachable */
a2 = a5; 
/* here the address of a5 overwrites address of a2-- This is how, a2 becomes unreachable */
a3 = a6; 
/* here the address of a6 overwrites address of a3-- This is how, a3 becomes unreachable */
----
}

This could be well understood with help of this image...
This is how garbage collector manages the de-allocation of memory. It could be called explicitly by calling  method java.lang.System.gc().

Did you like it ? Please reply/comment/suggest...
Let's share it to grow and to grow to share !



What is this pointer/reference in C++/Java?

Let's explore it !

Let's understand it, through an example, Look at this example. 
Here the method returns the account corresponding to maximum balance. 
                               


So it clear from this example that, the method find() is returning an object corresponding to maximum balance.Two objects are passed to it, one is coming as a parameter and the other is made available to the method implicitly, as find() is invoked with it. Here the explicit object which is coming as parameter is 'a2' , copied in a local object 'ax' and with 'a1' the find method is invoked, hence it is available to the method implicitly.
As 'a1' represents implicit object, it's address is stored in a system pointer called 'this' pointer. To get this object we need to apply ' value at address operator'(*). as show in this slide.

How did you find this post.. Please reply...

Sunday, March 13, 2016

What is polymorphism in C++/Java?

Dear Folks !
Polymorphism is an  important feature of object oriented programming paradigm. This makes the language dynamic.(due to this, easy up-gradation/extensibility of  software is possible).

The literal meaning is many forms, i.e one name - many forms. In programming context, it is one method/object with different behaviors under different contexts. In our day-to-day activities we often demonstrate this feature. This image would make us realize it.
Polymorphism can be implemented at compile-time  and run-time of the program. It basically depends on binding(or linking) time of a method call to method definition.

If the information, to bind a call to it's definition is available at compile-time of the program,then we can implement compile-time polymorphism.(static polymorphism).

In C++/Java we implement it, by function/method overloading. For overloading, the condition is that, the methods must have same method name, but vary at least with regard to any one criterion listed below...
 (i) Number of arguments
 (ii) Type of arguments
If we can create a mismatch among the methods being overloaded,  using these two parameters, then, the compiler can uses this, to discriminate the calls and accordingly bind the call to definitions at compile-time. 
Note: The return-type information is useless in overloading, hence bears no significance w.r.t compile-time polymorphism.

/* Let's demonstrate it in C++ */

float compuTax(float gross_sal)
{
 return 20*gross_sal/100;
}

float compuTax(float gross_sal, float bonus)
{
 return (20*gross_sal/100) + (30*bonus/100) ;
}

void main()
{
 -----
 -----
tax1=compuTax(650000);
tax2=compuTax(700000,299999);
-----
}
Notice here, the return type for both methods is same, still overloading  is possible. The mismatch is been created using argument numbers.
Let's check , how it works...

In C++, operator overloading uses compile-time polymorphism.

Now, Let's explore run-time polymorphism...

We know, if the mismatch is not created either in terms of number of arguments or type of arguments, then method overloading is not possible, as the compiler fall short of information to link the calls, to their respective definitions.In such scenarios since the compiler has no information, it postpones the job of binding till run-time of the program. At run-time, the system will link the method calls to the respective definitions, based on the information made available to  it during run-time.Hence it is called dynamic ploymorphism.
In C++ it is implemented using virtual functions, and in Java, it is implemented using dynamic dispatch of methods.
Let's see how it's implemeted in Java...

class Employee // super class
{
 protected double sal;
 void init(double x) { sal=x;}
 double compuTax(){ return 0.2*sal; }
}

class Manager extends Employee
{
 protected double bonus;
 void setBonus(double x){ bonus=x;}
 double compuTax(){return 0.2*sal + 0.3* bonus ;}
}
class DemoPoly
{
 public static void main(String args[])
 {
   Employee empref;
   Employee tom = new Employee();
   tom.init(50000);

   Manager jerry=new Manager();
   jerry.init(70000);
   jerry.setBonus(10000); 
   double tom_tax, jerry_tax;
  
   empref=tom;
   tom_tax= empref.compuTax();
   empref=jerry;
   jerry_tax=empref.compuTax();
   
   System.out.println("Tom has to pay a tax of "+tom_tax);
 System.out.println("Jerry has to pay a tax of "+jerry_tax);
 } // end of main method
}

Output
Tom has to pay a tax of 10000
Jerry has to pay a tax of 17000
You can notice here that the calls(in red) have same signature, i.e same argument type and number, as compiler is not able to bind, it postpones till run-time. The run-time system, checks what is being represented at this instant,by superclass (empref) reference, and then accordingly links and calls the method of that class/object.
If the superclass reference is representing employee, compuTax() of Employee is called, if it is representing manager, compuTax() of manager is called and so on...
You would appreciate this feature, after going through the following scenario.

Say, you want to add one more new class to your existing system, let's say class Supervisor, you will do it like this...

class Supervisor extends Employee
{
 protected double overtime_package;
 void setpackage(double x){ overtime_package=x;}
 double compuTax(){ return 0.2*sal + 0.15* overtime_package ;}
}

class DemoPoly
{
 public static void main(String args[])
 {
   Employee empref;
   Employee tom = new Employee();
   tom.init(50000);

   Manager jerry=new Manager();
   jerry.init(70000);
   jerry.setBonus(10000); 
   double tom_tax, jerry_tax,peter_tax;
  
   empref=tom;
   tom_tax= empref.compuTax();
   empref=jerry;
   jerry_tax=empref.compuTax();
   
   Supervisor peter=new Supervisor()
   empref=peter;
   peter_tax= empref.compuTax();
   System.out.println("Tom has to pay a tax of "+tom_tax);
   System.out.println("Jerry has to pay a tax of "+jerry_tax);
   System.out.println("Peter has to pay a tax of "+peter_tax);

 } // end of main method
}

This is how due to dynamic polymorphism, easy up-gradation or extensibility of software is possible. This is how we make the old code use new code, with little changes or no changes in existing code ...

How do you justify that, birds in this image are demonstrating polymorphic behavior !!!

Did you find this article worth reading  ?  please comment...
Let's share to grow and grow to share...

Wednesday, March 9, 2016

Classes and Objects in C++/Java

Dear Folks !
Classes and Objects form basis of object oriented programming(OOP), without this concept hardly any one can implement other features (like Data Abstraction, Encapsulation, Inheritance etc) of OOP. 
In the context of OOP, a Class is a group/collection of objects or things which exhibit similar characteristics. For instance a class of mobiles, class of birds etc.

In programming context, it represents a  factory of objects, i.e using a class one can create objects with required specifications(behavior),So, put in other words it is template or blueprint kind of thing using which you can create objects of certain behavior. The following image makes it clear how it can act as factory for objects...
Normally, class has three parameters. Namely
1. A unique class name
2. Attributes
3. Methods

A class must have unique name, it can not share it's name with any other class. For example, the name of class can be  Car, 
A class has a list of attributes,which are used to describe behavior of an object. Examples:
A class Mobile can have attributes like
RAM size, internal memory, battery life, camera pixels etc.
Similarly a class Account can have attributes like, cust_id, acc_no, acc_type, balance etc. 
The methods of class help to control the behavior of an object, there by allowing to modify the states of an object. Let's explore more about attribute and methods of class car. Look at the image ...


So here for class Car we have attributes like fuel(quantity/level) and maxspeed, so through these attributes we control the behavior of car.
For example, Through method setSpeed(),  if we set maxspeed as 120km/hr, then when we drive it, the maximum speed available would be 120km/hr and we can drive fast. where as if we set maxspeed as 30km/hr, then we drive slowly. You can notice here the behavior of an object car is controlled through methods of that class...
From the above discussion it is clear that an object is an entity/thing which has certain behavior, that can be controlled. It has states corresponding to attributes of class. The states of an object could be changed/modified through methods of class.This is how one can set the desired behavior to an object.

In a nutshell, we can say, object has three parameters, Namely
1. Identity( obtains from the class name)
2. States( obtains through the attributes of a class)
3. Behavior( can be controlled through the defined methods/functions of class).

Following example illustrates this concept in Java

class Account
{
 private String name;
 private double balance;
 void init(String sx, double x) { name=sx; balance=x;}
 void setNewBalance(double x){ balance=x;}
 void show(){ System.out.println(name+" has balance "+balance;}
}

class DemoAccount
{
 public static void main(String args[])
 {
  Account a1=new Account();
  Account a2=new Account();
  a1.init("Tom",200000);
  a2.init("Jerry",100);
  a1.show();
  a2.show();
 /* Now Tom is rich, behaving arrogantly, but Jerry is poor, waiting  for an opportunity, let's give him an opportunity to Jerry and  make him rich, let's change their behavior, */
 a1.setNewBalance(50);
 a2.setNewBalance(300000);
 a1.show();
 a2.show();
 /* Now you can see Jerry has good money, and has become rich, so his behavior changed from poorness to richness, but still Jerry is Humble and polite.*/
 }
}
Output
Tom has balance 200000
Jerry has balance 100
Tom has balance 50
Jerry has balance 300000

In conclusion, it is a backbone of OOP paradigm, and helps in Data Abstraction, Data Encapsulation and run-time polymorphism, which in turn provide extensiblity  of software easily.

How did you find this stuff ? Please comment and suggest if any improvements needed here...

Tuesday, March 8, 2016

What are the features of Object Oriented Programming ?

Object oriented programming(OOP) is a programming paradigm, in which data is of prime concern and action associated with that data is a secondary aspect. 
Where as in procedure oriented programming paradigm, focus will be on actions, rather than data/objects. This image clearly demonstrates both the paradigms,


The OOP paradigm is based on cognitive theory, which deals with, the nature of  human brain in recognizing and understanding the problem, by associating the objects in the problem domain.
The primary advantages of using this paradigm for software development are easy design, easy maintenance and easy up gradation of software. These advantages are outcome of implementing features of object oriented programming, namely

  • Data Abstraction
  • Data Encapsulation
  • Classes and Objects
  • Inheritance
  • Run-time polymorphism
Let's explore these one by one and see how they contribute in the process of software development.
(one  feature --- in one post)

Data Abstraction: 
It is the concept, in which an object is described with essential characteristics, without going into the background details of it. The irrelevant details/characteristics of an object are chopped-off and focus will be only on essential aspects. 

Let's understand data abstraction with the help of this image...


From the image it is clear that, over abstraction leads to lesser details and thus we fall short of information to understand, where as  under abstraction leads to more details, some which are not relevant to the problem in hand and creates confusion.

Thus to make our solution simple to understand and easy to use, we need to implement just data abstraction, it should not be neither over abstraction(too much chopping-off) nor under abstraction.


This depends on user requirements. What the user is demanding and if you are providing exactly that, then it is Data Abstraction, If you provide lesser features than those given by user then it over abstraction. Here the user fall short of some features and rejects your product/software/design.

If you provide more features than those given by the user then it is under abstraction, with this also, user is not happy, as he has more features, which he do not intended to have, so he dislike it,

Let's understand it by going through a scenario. Let's say you are suppose to gift a mobile to your sister and grandfather.If you are smart, you will buy a simple mobile for grandfather using which he can do necessary tasks like calling , messaging etc, and you will  buy a smart phone for your sister , which she can use for browsing, online shopping etc. Here you understood the needs of users pin pointedly and provided the solutions accordingly. This is just abstraction.

Let's say, if you have gifted a smart phone to your grandpa, then what would have happened ? Obviously , he would have confused with so many features and may not use it conveniently. This is what under abstraction.

The other case is, if you have gifted a simple mobile to your sister, she would have taken it to trash, as it is of no use to her other than basic calling and messaging. This is case of over abstraction.
Thus from the above discussion, it can concluded that, by implementing data abstraction , we achieve simple design/user interface for the software.

This is just an anlogy to make you understand the concept of abstraction, may not exactly depict the process.

Do you find this post useful? your comments and suggestions would contribute in improving the content of this blog.
Let's share to grow and grow to share...


Friday, March 4, 2016

What is the Lvalue required error in C/C++ ?


Dear Folks,

It is a common error encountered while learning C/C++ programming.C/C++ compilers flag this error whenever the program tries to modify the constant values.

Constant in programming context can be defined as a value, that does not change during program execution. In programming, constants are literal values and can be classified as below,



In programming, normally, when we define a mathematical expression, it has two components around assignment operator, one is the Lvaue and the other is Rvalue as shown in the image...
It is clear from the above expression that, the Lvaue is Left side component and Rvalue is the result of evaluation of right side component of an assignment(=).

Thus it can be concluded that, variables used in programming can be used as Lvalues as well as Rvalues, where as constants are always Rvalues they can not be used as Lvalues. If we try to use a constant as an Rvalue, the compiler demands you to provide a Lvalue, as a constant can not be modified.

for instance
int a,b;
a=5;  ----(1)// here 'a' is Lvalue and 5 is Rvalue
b=a;  ----(2)// here 'b 'is Lvalue and 'a' is Rvalue
Here we can notice that in equation(1) 'a' is used as Lvaule, and the same , is been used in equation(2) as Rvalue, So we say a variable can become Lvalue or Rvalue...

Let's say
#define SIZE 10 // this is how we define constants in C language, now SIZE is a constant
main()
{
  printf("%d\n", SIZE++);
}
This program is compiled with an error " Lvalue required", as we are trying to modify a constant.
SIZE++ is actually SIZE=SIZE+1 , here the constant is used as Rvalue, hence compiler raises an objection, that a constant can not be modified.

Similarly there is another scenario where we get this error very commonly, can you Guess ?

YES, you are right ! It is when you try to modify base address of an array by it's NAME. In programming, the base address of an array by array-name is constant. It can be copied in some  other variable and then can be modified.

 A sample program to  demonstrates this concept.
Program 1: Demo Lvalue required Error
Program 2: Demo Lvalue required Error
We can notice here, program:1 is compiled with an error Lvalue required, for the statement *(++x), as the program is modifying the base address by an array-name(x), where as program:2 is successfully compiled with no errors, and we get an output. In program:2, though, we are modifying the base address , the program is compiled with no errors, as it is done with another variable, not using an array-name.

Did you find this post useful ? Please reply through blog itself...
If any suggestions and comments, you are most welcome....



Thursday, March 3, 2016

Know how to swap two numbers using XOR operation !

Dear Folks,
Perhaps you are familiar how to swap two numbers without using a temporary variable using arithmetic operation... like
let's swap , a =5 and b=7

step 1: a:=a+b
step 2: b:=a-b
step 3: a:=a-b

step 1: a:=5+7  i.e a:=12
step 2: b:=12-7 i.e b:=5
step 3: a:=12-5 i.e a=:7
We can see both got swapped...

Let's see how we can swap using EX-OR bit wise operator, let's use cap(^) operator to represent EX-OR operation:
Truth Table of EX-OR
step 1: a:=a^b
step 2: b:=a^b
step 3: a:=a^b

step 1: a:=5^7  
101  
111
----------                                                   
010   // Refer truth table of EX-OR 
i.e a:=2

step 2: b:=2^7
010
111
----------
101 i.e b:=5

step 3: a:=2^5
010
101
----------
111 i.e a:=7


Note: This is for your information, but these are not at all practically suitable methods, as they add computational overhead, So in practice we must use a method which uses a temporary variable, as at low level, it is just a data transfer.

Revert me back with queries... and suggestions
I hope you liked it ! let me know it by replying through this blog itsef....
Thanks for visiting, if you like the blog, please subscribe...

Tuesday, March 1, 2016

What’s an Algorithm ?

Dear Folks, 
                        An algorithm is backbone of a program. Every program is an algorithm, but an algorithm is not a program. When we add syntactical aspects of a particular programming language to it, we call it as  a program. 

This is actually a name of a person called , Alkhowrizmi, an  Arab   mathematician   of the court of Mamun in Baghdad. His treatises on Hindu arithmetic and on algebra made him famous.He is said to  have given algebra  its  name, and the word algorithm issaid to have been derivedfrom his name. Much of the mathematical knowledge of medieval Europe was derived from Latintranslations of his works.

         Basically an algorithm is a precise set of instructions, to perform a particular task step by step. 
Let’s develop an algorithm to prepare a cup of coffee ...

Step 1: Start
Step 2: Take a cup-full hot milk
Step 3: Add a half tea spoon full coffee powder
Step 4: Add a tea-spoon full sugar
Step 5: Stir well, so that the coffee powder can mix properly with milk.
step 6: Stop
I guess a normal person agrees that, it is an algorithm, Believe me………                                           IT IS NOT AN ALGORITHM !!!
Because, It is  not precise !  as It does not specify quantity of milk,powder and sugar. Moreover how long I should stir, the time is also not specified. If dictated  to a normal person, he could prepare a cup of coffee, by using his common sense… but computer has no common sense kind of thing, so we must specify everything precisely, as a programmer, you  must always keep this point in mind that a computer is a garbage in garbage out....
Nothing should be vague. As the above set of steps are all vague, It can not be called an algorithm for preparing a cup of coffee. Let me demonstrate , how we develop the an algorithm for  of swapping two variables without using the third one.The image explains you, how to exchange contents of the two glasses.
From the image it clear that, to swap/exchange contents , we must use a temporary container. But in programming it is possible to swap/exchange without using a  temporary container. Let’s develop an algorithm to swap two numbers say A and B using temporary container....
Step 1: Start
Step 2: Let A:=5 and B:=7 and C be the temporary container
step 3: (Step 1 of image)  C := A
step 4:(Step 2 of image)  A := B
Step 5:(Step 3 of image)  B := C
Step 6: Print A and B
This will print A as 7 and B as 5. This is how we exchange/swap two variables using third variable. Here A is the first variable and B is the second variable and C is the third variable(temporary variable). This algorithm can be converted to a program, just by adding syntax of a given language.
// A Java program to swap two numbers using third variable
class DemoSwapping
{
public static void main(String[] args)
{
int A,B,C;
A=5;
B=7;
/* swap here */
  C = A;
  A = B;
  B = C;
System.out.print(“A=”+A);
System.out.println(“  B=”+B);
}// End of main method
}//End of class DemoSwapping : Output : A=7 B=5
Please give suggestions and comments through this blog itself... Thanks for reading...