Monday, 9 March 2015

Type casting with different types of type casting techniques

Type casting with different types of type casting techniques with examples:

 Typecasting is the technique that is used to convert the data explicitly.
See the below example, in this example we are converting double to integer value
#include "stdafx.h"
#include <iostream>
using namespace std;
int main ()
  double dData = 100.90;
  int iVal = 0;
  iVal = int (dData);
  iVal = (int) dData;
  getchar ();
  return 0;

The functionality of these generic forms of type-casting 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 compiles without errors:

#include "stdafx.h"
#include <iostream>
using namespace std;
class myFun {
    double i,j;
class Aurthimetic {
  int x,y;
  Aurthimetic (int a, int b)
    { x = a; y = b; }
  int GetResult ()
    { return x + y;}
int main ()
  myFun ocFun;
  Aurthimetic * ocAdd;
  ocAdd = (Aurthimetic*) &ocFun;
  cout << ocAdd->GetResult();
  getchar ();
  return 0;

The above program declares a pointer to Addition class, but then it assigns to it a reference to an object of another unrelated type using explicit type-casting:
 ocAdd = (Aurthimetic*) &ocFun;

This type of explicit casting will produce some runtime errors with some other unexpected results.
So to resolve these types of problems between the classes, in C++ we have four casting operators as shown below

const_cast <new_type> (expression);

dynamic_cast <new_type> (expression);

reinterpret_cast <new_type> (expression);

static_cast <new_type> (expression);

Brief description about each type:

const_cast<type> (expr): The const_cast operator is used to explicitly override const and/or volatile in a cast. The target type must be the same as the source type except for the alteration of its const or volatile attributes. This type of casting manipulates the const attribute of the passed object, either to be set or removed.

dynamic_cast<type> (expr): The dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a A* pointer into a B* pointer only if the object being pointed to actually is a B object.

reinterpret_cast<type> (expr): The reinterpret_cast operator changes a pointer to any other type of pointer. It also allows casting from pointer to an integer type and vice versa.

static_cast<type> (expr): The static_cast operator performs a nonpolymorphic cast. For example, it can be used to cast a base class pointer into a derived class pointer.

dynamic_cast with example:

I'll provide a reference link here soon!

static_cast with example:
static_cast can perform conversions between pointers to related classes, not only upcasts but also downcasts.

No checks are performed during runtime to guarantee that the object being converted is in fact a full object of the destination type.
class MyBase {
class MyDerived: public MyBase {};

MyBase * pcBase = new MyBase;

MyDerived *pcDerived = static_cast<MyDerived*>(pcBase); 
This would be valid code, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.

Therefore, static_cast is able to perform with pointers to classes not only the conversions allowed implicitly, but also their opposite conversions.

static_cast is also able to perform all conversions allowed implicitly (not only those with pointers to classes), and is also able to perform the opposite of these. It can:

Convert from void* to any pointer type. In this case, it guarantees that if the void* value was obtained by converting from that same pointer type, the resulting pointer value is the same.
Convert integers, floating-point values and enum types to enum types.
Additionally, static_cast can also perform the following:
Explicitly call a single-argument constructor or a conversion operator.
Convert to rvalue references.
Convert enum class values into integers or floating-point values.
Convert any type to void, evaluating and discarding the value.

reinterpret_cast with Example:
We can convert any ppoiunter type to any other pointer type using reinterpret_cast. 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 guaranteed to be able to be cast back to a valid pointer.
See the below example:
class ClsA {  /* your class code */ };

class ClsB { /* your class code */  };

ClsA *pcA = new ClsA;

ClsB *pcB = reinterpret_cast<ClsB*>(pcA); 

This code compiles, although it does not make much sense, since now b points to an object of a totally unrelated and likely incompatible class. Dereferencing b is unsafe.

const_cast with example:

This type of casting manipulates the constness of the object pointed by a pointer, either to be set or to be removed. See the below code snippet
#include "stdafx.h"
#include <iostream>
#include <typeinfo>
using namespace std;
void GetVal (char * pcchStr)
  { cout << pcchStr << '\n'; }
int main () {
  const char * pcchVal = "sample text";
  GetVal ( const_cast<char *> (pcchVal) );
  getchar ();
  return 0;

No comments: