Tag Archives: c++

Byte packing !

Hello friends ,

I was studing C++ late in night and I faced a little weird situation . I saw a code as follows:

class check
int i;
float j;
char k;
int main()
check c;
return 0;

As I was expecting the output 9,9 , but it didn’t give the same on my linux machine.

And then I came to know that byte packing is done here .

Linux  being a 32-bit OS , so the object would be aligned on a 4-byte boundary.

Hence I got the output 12,12.

Isn’t it memory consuming ?

Well , we can overcome from this situation by using pragma.

We can force the alignment on a 1-byte boundary. To do this , we have to use

#pragma pack(1)  just before the class declaration.But friends , one more thing is still left, you can’t use #pragma pack with any random number. The number in the paranthesis must be a small power of two. Otherwise you may get the warning stating the same.

So don’t wait , open your text editor and try this . ♥

Leave a comment

Filed under Tech-Bowl

Conversion operator

Hello squids ,

Many of you ,who are studing/studied C++ , may be aware of conversion operator.

In short it may be described as :

A conversion operator can be thought of as a user-defined typecasting operator; it converts its object to a different type in contexts that require that specific type.

And that specific type may be built in as well as user defined .

I like this feature because of the flexibility that it provides to this programming language.

Here I am giving an example which will help you for better understanding of this operator.

class Mystring
char *s;
int size;
Mystring(const char *);
operator const char * () { return s; }

int main()
Mystring str(“hello world”);
int n = strcmp(str, “Hello”);
return 0;

In this example constructor is taking argument const char * and in main “hello world” is passed as an argument in the object.But in next line we are trying to compare a string with an object, which will cause an error , if we don’t use the conversion operator.

So , here conversion operator comes in action and it converts the object into a constant string.

The prototype of conversion function is –

operator type()   {return value;}

here value is the value of class after conversion .type is the data type in which object is to be converted .

Conversion operators differ from ordinary overloaded operators in two ways. First, a conversion operator has no return value (not even void). The return value is inferred from the operator’s name. Secondly, a conversion operator takes no arguments. Conversion operators can convert their objects to any given type, fundamental and user-defined.

Hope this’ll help you guys .

Leave a comment

Filed under Tech-Bowl