≡ Menu

How to Convert Data Types in C++ with TypeCasting Operator Example

Converting data types from one to another is a most basic aspect for any programmers.

First, let us start with the basics.

int nNumber;

The following are few things to keep in mind for the above line of code:

  • Data type of nNumber is int, which means that we are dealing with number that will be good for natural numbers from certain range. Sometimes, this is not good, as this is machine dependent, and when you use 32 bit machine, it will be different than when you use 64 bit machine.
  • For this variable, a place is reserved in memory and that place has an address. To obtain the address for a variable you could use operator that will return the address of the variable. For example: &nNumber. This is very important operator and it is used to connect the pointer and some other object in memory.
  • When you write something like this nNumber=10, system will interpret array of ones and zeros in certain way. Well they will be interpreted as int-s, and it call that array of zeros and ones nNumber or change value 10 into something else.

There are pointers as well, they are not storing the value, but they contain the address of some object in the memory. To define the pointer you could do something like this:

int* ptr;

This code is reserving the place for addresses that will point to some int data. There are also void pointers, they have no type to point to, but they could be converted to some pointer of certain data type.

Then to work with the pointers, you need to connect it to some object in the memory that has address that could be done like this:

ptr = & nNumber;

Now you connected object of int type in the memory. If pointer has nothing to point to, it will use NULL address, and new C++11 standard has new way for that. You are advised to use: nullptr.

Now, let us move to constants. For example, pi is a constant that is used to calculate area of the circle and in some other calculations.

To define a constant value, we could use macro like this:

#define EXIT_SUCCESS 0

Now, every time when EXIT_SUCCESS is found in the code it will be replaced with 0.

This way you don’t see what is the type of const, so you could define the constant value like this:

const unsigned long long cullConstantValue = 011235813;

You can also figure out the size of a variable as shown below:

sizeof(someObject);

When you want to define your own datatype, do the following:

typedef unsigned long long int myDataType;

This way you don’t have to types those very long data types every time, and also this is easy to understand.

And if you are familiar with classes, then it would be appropriate to compare class to data type and object to variable.

In the next few lines we will also need from you to understand the concept of classes, inheritance and few other things.

How and Why to Convert Data Types

When you have an expression that has few different data types in it, you could end up with lost precision. That is one of the reason why you need data conversion. There are also some other situations that require from you to convert data types as well.

So, how do we convert data types? You could do something like this:

int nNumber = 1;

double dNumber =(double) nNumber;

This is not only way and it is still possible to do it in C++11, we could write it like this, as well: double(nNumber);

When you convert 8-bit to 16-bit data type, it could be done as there is enough space. When you convert 16-bit data type to 8-bit data type, there will be some loss. In that case, you’ll get a warning.

We have few advanced ways to achieve same result:

  • static_cast
  • const_cast
  • dynamic_cast
  • reinterpret_cast

The static_cast is used when you need to change the type of the variable.

If you are in a situation where you need to change the state of const object, you could use const_cast.

When you need to change the types of objects in manner of hierarchy with the respect to inheritance, you could use dynamic_cast.

If you try to change type of pointers, without respect to inheritance or classes being related, you could use reinterpret_cast.

The following example is for static_cast:

int    nNumber = 1788;
double dNumber = static_cast<double>(nNumber);

int nI=1,
    nJ=5;

double dResult1 = static_cast<double> (nI)/nJ;
double dResult2 = double(nI)/nJ;

It is possible to use static_cast with classes as shown below:

class CParent { ...//some code that goes in this class};
class CChild: public CParent { ...//some code that goes with this one};

CParent* ptrParent = new CParent;
CChild*  ptrChild  = static_cast< CChild*>(ptrParent);

But, why do we want to do the above?

For const cast, it changes something that is constant. Example for that could be the data type that is passed to function that expects some non constant data type.

Also, it could be used in the following situation.

const double dGravity = 9.81;

double *ptrGravity = const_cast<double*>(dGravity);

*ptrGravity = 10;

cout<<dGravity<<endl;

The dynamic cast will be used in situations where you have pointers or references to classes. Parent class should have one virtual function, and it gets done in run time. It is used for changing the type from CParent to CChiled and vice-versa.

CChild* ptrChild = dynamic_cast <CChild*> (ptrParent);

The following could be used with void pointers as well.

When we deal with reinterpret cast and objects, we need to be careful as it could also change types of non related classes.

class CSomeClass { ...//some code that goes in this class};
class COtherClass{ ...//some code that goes with this one};

CSomeClass*   ptrSC = new CSomeClass;
COtherClass*  ptrOC = reinterpret_cast< COtherClass*> (ptrSC);

If C++11 is supported, I would like to mention few new concepts.

When you are dealing with situation where you need to create the variable from the context of expression you could use the auto type as shown below:

auto aVariable = 11;
auto aVariable = 2.111719;
auto aVariable = ‘c';

The first aVariable will be int type, the second would be double and the third char.

If you need to figure out the type of the variable in C++11 you could use decltype as shown below:

decltype(someType) sameType;

Functions Used for Conversions

In the <stdlib.h> there are few interesting functions that could be used to convert data types:

  • atof(charArray) will transform the array in style of C language into float.
  • atoi(charArray) will transform the array of chars into the int.
  • atol(charArray) performs the conversion into the long data type.
  • from C99 there should be atoll.
  • itoa(nNumber) should change int into the array of chars.

Those functions and few others are usually used in C style programming, but they still have place in C++ programs.

Overloading Operator Type() IN class

If you create a class, it could have overloaded operator (). So, if you need to use implicit conversion, it could be achieved with constructor that is used for initialization, and if you are having the problems with this, you could define explicit constructor, this would prevent the implicit conversion to happen.

Why would you prevent implicit conversion? Well there are situations in which you would not have expected results, to avoid that you just type explicit and the implicit conversion is prevented.

The explicit conversion, could be achieved with overloading of the operator(), which is the operator of casting.

The following example explains this from Object Orientated Programming point of view:

#include <iostream>

using namespace std;

class CKelvin
{
double dK;

public:
 CKelvin(double Celzijus=0)
{
 dK = Celzijus + 273.15;
}
operator double() { return dK;}

};

int
main(void)
{
  double dCelziusDegree;
  cout<<"Input the temperature in Celzius->";
  cin>>dCelziusDegree;

  CKelvin K(dCelziusDegree);

  cout<<"In Celzius it is="
  	<<double(K)-273.15
  	<<"In Kelvin it is="
  	<<endl
  	<<double(K)
  	<<endl;

  return EXIT_SUCCESS;
}
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • duskoKoscica June 13, 2014, 12:38 am

    It might be good idea to create table and have it somewhere handy, of converting data types.
    You might find some of the results interesting to.

  • Chris Arena June 13, 2014, 8:02 am

    Your example of a cast from a parent to a child class via static cast compiles but is wrong to do. Providing a poor example which will actually work in a very narrow set of circumstances, and not explaining those circumstances does a disservice to your readers.

    The details of when this and the other cast statements are appropriate are the real gold in C++. If you’re going to provide examples, they should represent the best practice, and you should explain why. If space permits, you should explain what is poor practice too.

    Chris Arena
    Portsmouth, Rhode Island

  • antonio June 17, 2014, 3:14 am

    I have rather practical approach somesing like rule of thumb for casting.
    It goes something like this:
    If I need to change the constantnes of something I use const_cast.
    If I need to change usuall types I use static_cast .
    When I need to change the pointeres or referenceses of polimorfic classes I use the dynamic_cast, but it will do some checks and it will be casted in run time.
    The static cast I try before reinterpret_cast and most time it is sign that there is error in design so I try to use void pointer to…
    Not sure it is alweys used in programs, I try to avoid changing data types more in C++ it is bit different than in C language, it is generally less used.

  • duskoKoscica June 21, 2014, 2:57 am

    @Chris Arena
    For this case of using static cast I have not provided a long explanation, because I would prefer that you don’t do it like that. So, it is example of what it could be done, and it should be undesanded just like that, which sould have been obviosus from the artticle.
    In most cases you should avoid the casting, because it is last resort and sometimes it is just a sign of bad designe. But sometimes people do it.
    There are some improvements that I still wait to be done.

    In most cases people act like Antonio. It is like that case of long definitions that you learn for exam, and after you just apply what is left. In the way it is cimilar to that case of learning to fly and fight and then all those roles are replaced with some practical things.

    The explanations are not very long, because they are lefto to the reader to explore and broaden them. It might be best for you to do those things on your own. And also I have done it in the way that will give the reader more chance to explore on its own. That table could be done, but it is left for the reader to…

    And I still wait to some improvements I have sent to Ramesh but somehow he is kind of buzzy.

  • duskoKoscica June 21, 2014, 3:44 am

    It could bee compared to bar where you have puritan crowd that do only the things that are said to be done and they do it the way you have asked them to do it in that way.c
    But there are crowds that are bit shady and some are goofy etc …
    Sometimes you benefit from those other crowds and sometimes you fail so bad that it hurts for months…
    Yes it is kid of a gamble. I have seen so many articles where tsay all and sometimes all what you are not able to do or not suppose to to. Then one day you do it what they say not to do and it could be done like that,
    Now it is not recommended to cast like (type) someVariable but that way still make my day every time I do it like that. It is from C days but it still could be done in that way.
    In my opinion programming is highly creative thing, but different and also similar to math. If wish to become the programmer, a lot of things are practical.
    Things that are not supported now are not supported now, that dos not mean that they will not be supported in the future.

  • duskoKoscica June 22, 2014, 12:30 am

    Ok, now I see there are few changes done on the article THX to Ramesh.

    And one more thing about converting data types.
    There are two basic cases, when you convert data that is stored in variable, you could have tree cases> you are broadening the type like from int to double or some other type that occupy more space, the second case is when you try to change types that are exact same size in memory, and the third case is when you don’t have enough space, so you would lose some zeros and ones that would be necessary.
    The second converting problem is when you transform the pointers, they hold the address of some object in memory so it is easy to convert them, but you should be careful that something strange does not happen.
    And there are situations that are odd. You could convert pointer into some data type and also some data type into pointer.
    This might be fun, but caution is adviced when you do fun things.
    If yo fill like asking questions don’t keep them for you self, but it is good to try to find an answer you self to…

    Have fun!