Monday, July 25, 2011

Type Casting in C++

Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:

Implicit Conversion

Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:

short a=2000;
int b;
b=a;

Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example:


class A {};
class B { public: B (A a) {} };

A a;
B b=a;

Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.

Explicit Conversion

C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:

short a=2000;
int b;
b = (int) a; // c-like cast notation
b = int (a); // functional notation

The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct:

// class type-casting
#include <iostream>using namespace std;

class CDummy {
float i,j;
};

class CAddition {
int x,y;
public:
CAddition (int a, int b) { x=a; y=b; }
int result() { return x+y;}
};

int main () {
CDummy d;
CAddition * padd;
padd = (CAddition*) &d;
cout << padd->result();
return 0;
}

The program declares a pointer to CAddition, but then it assigns to it a reference to an object of another incompatible type using explicit type-casting:

padd = (CAddition*) &d;

Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member result will produce either a run-time error or a unexpected result.

In order to control these types of conversions between classes, we have four specific casting operators: dynamic_cast, reinterpret_cast, static_cast and const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.

dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)

The traditional type-casting equivalents to these expressions would be:

(new_type) expression
new_type (expression)

but each one with its own special characteristics:

Dynamic Cast

dynamic cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

Therefore, dynamic_cast is always successful when we cast a class to one of its base classes:

class CBase { };
class CDerived: public CBase { };

CBase b; CBase* pb;
CDerived d; CDerived* pd;

pb = dynamic_cast<CBase*>(&d); // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived

The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.

When a class is polymorphic, dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class:


// dynamic_cast
#include <iostream>#include <exception>using namespace std;

class CBase { virtual void dummy() {} };
class CDerived: public CBase { int a; };

int main () {
try {
CBase * pba = new CDerived;
CBase * pbb = new CBase;
CDerived * pd;

pd = dynamic_cast<CDerived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast" << endl;

pd = dynamic_cast<CDerived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast" << endl;

} catch (exception& e) {cout << "Exception: " << e.what();}
return 0;
}

Compatibility note:

dynamic_cast
requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using dynamic_cast to work properly.

The code tries to perform two dynamic casts from pointer objects of type CBase* (pba and pbb) to a pointer object of type CDerived*, but only the first one is successful. Notice their respective initializations:

CBase * pba = new CDerived;
CBase * pbb = new CBase;

Even though both are pointers of type CBase*, pba points to an object of type CDerived, while pbb points to an object of type CBase. Thus, when their respective type-castings are performed using dynamic_cast, pba is pointing to a full object of class CDerived, whereas pbb is pointing to an object of class CBase, which is an incomplete object of class CDerived.

When dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_cast is thrown instead.

dynamic_cast can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers (void*).

static_cast

static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.


class CBase {};
class CDerived: public CBase {};
CBase * a = new CBase;
CDerived * b = static_cast<CDerived*>(a);

This would be valid, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.

static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types:

double d=3.14159265;
int i = static_cast<int>(d);

Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.

reinterpret_cast

reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.

It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer.

The conversions that can be performed by reinterpret_cast but not by static_cast have no specific uses in C++ are low-level operations, whose interpretation results in code which is generally system-specific, and thus non-portable. For example:


class A {};
class B {};
A * a = new A;
B * b = reinterpret_cast<B*>(a);

This is valid C++ code, although it does not make much sense, since now we have a pointer that points to an object of an incompatible class, and thus dereferencing it is unsafe.

const_cast

This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter:


// const_cast
#include <iostream>using namespace std;

void print (char * str)
{
cout << str << endl;
}

int main () {
const char * c = "sample text";
print ( const_cast<char *> (c) );
return 0;
}

typeid

typeid allows to check the type of an expression:

typeid (expression)

This operator returns a reference to a constant object of type type_info that is defined in the standard header file <typeinfo>. This returned value can be compared with another one using operators == and != or can serve to obtain a null-terminated character sequence representing the data type or class name by using its name() member.


// typeid
#include <iostream>#include <typeinfo>using namespace std;

int main () {
int * a,b;
a=0; b=0;
if (typeid(a) != typeid(b))
{
cout << "a and b are of different types:\n";
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
}
return 0;
}

When typeid is applied to classes typeid uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object:


// typeid, polymorphic class
#include <iostream>#include <typeinfo>#include <exception>using namespace std;

class CBase { virtual void f(){} };
class CDerived : public CBase {};

int main () {
try {
CBase* a = new CBase;
CBase* b = new CDerived;
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
cout << "*a is: " << typeid(*a).name() << '\n';
cout << "*b is: " << typeid(*b).name() << '\n';
} catch (exception& e) { cout << "Exception: " << e.what() << endl; }
return 0;
}

Note: The string returned by member name of type_info depends on the specific implementation of your compiler and library. It is not necessarily a simple string with its typical type name, like in the compiler used to produce this output.

Notice how the type that typeid considers for pointers is the pointer type itself (both a and b are of type class CBase *). However, when typeid is applied to objects (like *a and *b) typeid yields their dynamic type (i.e. the type of their most derived complete object).

If the type typeid evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid exception.

What our compiler returned in the calls type_info::name in the this example, our compiler generated names that are easily understandable by humans, but this is not a requirement: a compiler may just return any string.

Monday, July 18, 2011

My Favorite Android Games

There are thousands of games out there in market most of them are paid or free, but which one do you like, I did refer to people’s blog to find it out, and many like variety of games. But here is the list of paid and free games which I liked, and I play almost every day.

Angry Birds RioAngry Birds Rio is a variant of original Angry birds, so obviously it’s a FUN game, here you have different types of levels which makes it more attractive compared to the original game. They keep updating, so more fun to come in future. It’s free game but comes with Ads, if you disable the data connection while playing this game then you won’t see any ads, that’s the best way to deal with it.

Angry Birds SeasonsAngry Birds Seasons is another variant where in you can play them in different seasons such as Christmas, in snow falls etc., more or less same as the original one, but here you have some bonus levels if you complete all levels in 3 stars, so kind of challenging and keeps the game spirit on till the end of the game

Angry BirdsAngry Birds (Original) is a fun game, and you will get addicted to this game so fast that every night you have to play this before going to sleep, that’s the level of addiction.

Its whole aim is to use some physics knowledge and make the birds jump on the pigs and destroy them, who takes the eggs of these birds. There will be so many obstacles when you try to destroy them, so plan well and achieve the goal.

Bebbled

Bebbled may not be interesting to that extent, but it’s a good time pass game. There is a target pointes to be made for each level, and until you make those many points you wont be allowed to go to next level. You need to touch the bubbles of the same color to make them disappear and make points out of it. More bubbles of same colors come together the more points you get.

Bonsai Blast

Bonsai Blast is the ZUMA game which we use to play in computers, where there would be a FROG at the center and colored balls would come and you need to shoot them before reaching the end point. If you make the balls of same color count more than three, then they disappear, lot more weapons etc., are there but you need to install it to explore. It is good one, but not as good as the ZUMA, but still a time pass game.

Bubble Blast 2

Bubble Blast 2, I have never played the first version. This one has lot of levels, may be I would never be able to complete. Its just a time pass game, you don’t need to know anything, and its very difficult to plan the game also, but over all it’s a time pass game. Keep touching the bubbles and they grow and finally blast, there are some restrictions on the number of touches you need to finish blasting all the bubbles, sometimes if becomes so difficult that you may have to take an hint. Only one hint per day.

Klondike Solitaire

Klondike Solitaire  is the best solitaire game I have come across for android devices, and this one is simple and intuitive, and easy to use game. A very good time pass game. Levels are somewhat difficult.

Just disable the data connections, else the ads would be irritating.

Magic Marker

Magic Marker is not a game, but it’s a FUN app, with which you can make your phone a drawing board, and draw in different colors, which come as magic lights. If you want to write something and show to someone special may be this would come in handy.

I have the pretty old version which does not have ads, but recent version comes with ads, so you may have some irritating ads popping up in the screen.

Need for Speed Shift

Need For Speed (NFS) Shift, if you are a fan of NFS and or a fan of racing, then this is one game you must buy, such an awesome graphics and such a wonderful game play, you would love it.

There are different tracks and different cars. You need to buy the cars from the money you make from racing and build your career.

Paper Toss

Paper Toss is an game for time pass when you don’t have any work to do. It’s as simple as throwing a paper into a dust bin.

There are different levels such as office, toilet, airport, basement etc., where the distance would be different and the fan would be placed in different locations.

Pool Master Pro

Pool Master Pro is the best pool game I have come across for android. It has such awesome graphics that you keep playing and get addicted to it.

There is one more game which is 3D but then its not as good as this. Its free and ad free. So go for it.

 

Slice It

Slice it! is a game mostly for kids, but still it’s a FUN game you can play. You will be given objects of different shape and you need to slice them into N equal parts by certain number of counts.

Initially the game would be easier, and it keeps becoming complex as you go up. You may have to check your geometric skills once again. Its not as simple as slicing a piece of cake. Mind it!

Sunday, July 17, 2011

Windows SkyDrive and Sync Storage

Now Microsoft has introduced an upgraded version of Live SkyDrive, a free online file storage service, that looks like a perfect choice at the moment for several reasons.

  • You get 25 GB of free online storage space for your documents, photos, and all other files - the previous limit was 5 GB. Now you have 5GB sync storage and you can use it as a replacement to Dropbox and keep all your file in sync across your computers using Live Mesh.
  • You have the option to download an entire folder on SkyDrive as a local zip file - huge time saver.
  • You can upload files to SkyDrive through Windows Explorer itself through Gladinet - it's just like mapping a folder on the network drive.
  • SkyDrive is like a social network for files. You can see files that your friends have shared on SkyDrive through your own Live Profile page (similar to Friend updates in Facebook).
  • SkyDrive is Microsoft service and an integral part of their larger Windows Live strategy so you really don't have to worry about its future existence.
  • Microsoft will soon offer an Online Office suite (like Google Docs) and it's a no brainer that documents uploaded to SkyDrive will be accessible from Online Office and vice-versa. Thus you indirectly get more storage space for documents.
  • SkyDrive has no real competition. Google and Yahoo do not have a presence in the online file storage market while services like DropBox, Mozy, Box.net, etc. offer only limited space (couple of gigs.) to free users.

So, over all it’s the best cloud storage as of now, as good as Google Docs, Microsoft is trying his best to come back again in the battle on the clouds.

Setup Hot mail on your Android device

This solution article provided information on how to setup your Hotmail account on Android phones.

Account settings and their level of support will vary across Android phones. While the steps to configure push email with synced contacts and calendar will vary, we have found these steps to work across a number of phones:

  1. Select “Email” client on phone.
  2. Press menu and select “Add account”
  3. Enter full Hotmail address: e.g. username@hotmail.com or username@live.com
  4. Enter password
  5. Select “Manual setup”
  6. Select “Exchange” when prompted for “What type of account is this?”
  7. Domain/Username, enter full Hotmail address: e.g. username@hotmail.com. (Note: if the device only says “Domain”, it should be left blank. If the device says “Username”, then enter the full Hotmail address. On some devices, the Domain/Username may be pre-populated incorrectly and should be erased.
  8. Type in password. (may already be filled in)
  9. Server name. Enter: m.hotmail.com for server name. (Note: this field may be pre-populated incorrectly depending on device).
  10. Make sure box “Use secure connection (SSL)” is checked.
  11. Select “Next”
  12. Select desired account options for inbox checking frequency, number of days to synchronize, send email by default, notifications and contacts/calendar sync. Select “Next”
  13. Depending on device you may be prompted for account color and account name (e.g. “Hotmail”)
  14. Select “Next” and your Hotmail is set-up and ready to go!

If these steps aren’t working, you can always access Hotmail through your phones browser at www.hotmail.com

Google and Family Planning!– Interesting answer

The following question is reputedly one of many that Google may ask prospective job candidates:

Imagine a country in which every family continues to have children until they have a boy. If they have a girl, they have another child, and continue until they have a boy, then they stop. What is the proportion of boys to girls in the country? You should assume that there is an equal probability of having a boy or a girl.

The question has been discussed at length on the Internet and this site is one of many that provide an answer. The answer is correct (approximately the same number of boys and girls) but I doubt whether the way it is derived would help to get you a job with Google. There are numerous other similar posts, most of which give the correct answer, but all but a few miss what I believe is the point of the question. It is an example of misdirection; the question describes a strategy for ensuring that all families have exactly one boy and zero or more girls, but what it asks for is the overall distribution of boys and girls in the country as a whole. The way the question is stated leads you to believe that the strategy will affect the overall distribution - but does it? Anyone with some knowledge of probability should then realise that no strategy that involves stopping after a certain number of children can affect the overall proportion, because all births are independent events. In the population as a whole the probability that the next child, born anywhere in the country, will be a boy is 0.5, regardless of how many boys or girls have already been born, so the proportion will be 50:50. Of course the proportion will rarely be exactly equal because the gender of the children are random events, in fact they form a binomial distribution, but for large populations it will be very close to 50:50.

To many people this is counter intuitive - probably because the strategy clearly does affect the make up of every individual family. Consider another country where they adopt the strategy of stopping after having exactly two girls. The only family distribution you would find on both countries would be two girls and one boy (but in a different order); the overall distribution however would still be 50:50.