Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: Object Oriented Programming
Expertise: Beginner
Dec 16, 1999

Equivalent functions for Unchecked Conversion

Question:

Are there any functions/libraries that can perform the Unchecked_Conversion function in Ada? We are writing a program that will read a bitstream. Upon determining the type, we want to able to sort of "cast" this bitstream to the correct object in C++.

Answer:

Sure there is a way to do that. However, perhaps I should explain what Unchecked_Conversion in Ada does, for C++ programmers who aren't fluent speakers of Ada.

Ada is a strongly-typed language. Therefore, it is does not allow the programmer to assign variables of different types to one another. For example, assigning a variable of type Float to a variable of type Integer requires an explicit cast. In C++, on the other hand, the cast isn't required in this case; it's performed implicitly.

Of course, real world programming requires some bit fiddling tricks and brute force casts, especially when dealing with low level functions that de-serialize objects from a stream of bits. For this purpose, Ada has the generic procedure Unchecked_Conversion, which takes as an argument one type, and returns another. The only constraint on this is that they must be the same size.

There are two ways to achieve this in C++. The first consists of using memcpy. However, this is kludgy and requires a function call with its associated overhead.

The second way relies on the built-in operator reinterpret_cast. As the name suggests, this operator casts one type to another by interpreting the bit pattern of the argument.

In general, you can convert non-related types by using reinterpret_cast to coerce the source's pointer to the target's pointer, and then dereference the resultant pointer. Thus, to convert a stream of bytes into a Person object, you would do the following:

struct Person{
 int age; 
 char name[20];
};
void cast(unsigned char * stream)
{
  Person per = *reinterpret_cast < Person* > (stream);
}

reinterpret_cast takes the argument stream (which is a pointer to char), coerces it to a pointer to Person, the target type (specified in the angle brackets) and then, the resultant pointer is dereferenced (the asterisk before reinterpret_cast). The operation yields a temporary object of type Person that is assigned to a Person object per. Unlike Ada, C++ does not require that the source and the target types have the same size; rather, C++ is true to the "trust the programmer" idiom.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date