#include<iostream>
using namespace std;
class Nibble
{
   private:
           union
           {
             int number : 4;
           };
   public:
          Nibble(int=0);
          friend ostream& operator<<(ostream&,const Nibble&);
          friend istream& operator>>(istream&,Nibble&);
};

inline Nibble::Nibble(int n) : number(n) { cout << "constructor.." << endl;}

ostream& operator<<(ostream& nout,const Nibble& n)
{
   return nout << n.number;
}

istream& operator>>(istream& nin,Nibble& n)
{
/* error here
 // error : In function `std::istream& operator>>(std::istream&, Nibble&)': 
 //cannot bind bitfield `n->Nibble::<anonymous>.Nibble::<anonymous union>::number' to `int&' 
*/

  return nin >> n.number;
}

int main()
{
    Nibble n1;
    cin >> n1;
    cout << "Value of Nibble is:" << n1 << endl;
    getchar();
    return 0;
}

Recommended Answers

All 19 Replies

Post the errors and a description of your problem/question.

edit: Sorry, didn't see the comments in your code. Still good to post a description of the issue though.

I see a couple of strange things, but the one related to your union:

union
{
int number : 4;
};

What are you trying to do with the colon? Also, I don't believe there's a point to a union with only one element.

I think the error may be caused because the overloaded operator you're defining is a global function, and it's trying to access a private member of a nibble.

What are you trying to do with the colon? Also, I don't believe there's a point to a union with only one element.

I'd like to know this myself. I typically don't see the colon used in unions/structs. I guess it's something I need to study.

I think the error may be caused because the overloaded operator you're defining is a global function, and it's trying to access a private member of a nibble.

Well, I don't agree with this. The streams are declared friends of the class Nibble so they should have the right to access private data. Here's the modified code, where the union yields a variable that simply holds an int--

#include<iostream>
using namespace std;
class Nibble
{
   private:
           union
           {
             int number;
           };
   public:
          Nibble(int=0);
          friend ostream& operator<<(ostream&,const Nibble&);
          friend istream& operator>>(istream&,Nibble&);
};

inline Nibble::Nibble(int n) : number(n) { cout << "constructor.." << endl;}

ostream& operator<<(ostream& nout,const Nibble& n)
{
   return nout << n.number;
}

istream& operator>>(istream& nin,Nibble& n)
{
/* error here
 // error : In function `std::istream& operator>>(std::istream&, Nibble&)':
 //cannot bind bitfield `n->Nibble::<anonymous>.Nibble::<anonymous union>::number' to `int&'
*/

  return nin >> n.number;
}

int main()
{
    Nibble n1;
    cin >> n1;
    cout << "Value of Nibble is:" << n1 << endl;
    getchar();
    return 0;
}

--it compiles, though it may not be accurate to the definition of a Nibble.

Edit: And from what I understand about unions, they're used under certain circumstances, for example--

*When data needs to be packed (Memory space is shared across data)
*In extension to packed data, Unions are used in concurrent situations (when information is sent/received quickly - a Union is preferable).

I only know of the second case because of what I typically see in FAQ's explaining the usage of Unions, as well as looking at information such as key events where information is briefly used. I suppose Unions act as a placeholder for data and concurrent data - that is constantly changing.

I'm not saying the use of Unions are limited to just these tasks, it's just what I see the most often.

Well, I don't agree with this. The streams are declared friends of the class Nibble so they should have the right to access private data. Here's the modified code, where the union yields a variable that simply holds an int--

Oh, right. At a glance I thought they were method declarations, not prototypes for global functions.

Sorry Guys! I should have to write some description abt my problem but I forgot!
really speaking I am new to use this Forum! so pls forgive me for that trouble, I am learning yaaar!

what are you trying to do with the colon? Also, I don't believe there's a point to a union with only one element.

I agree there is no point! But we can not use bit field like this without union/structure!
e.g int num : 4; // illegal

I'd like to know this myself. I typically don't see the colon used in unions/structs. I guess it's something I need to study.

union
{
  int bits4 : 4;
}

This definition causes 'bits4' to contain one 4-bit fields. Now you can use the usual union membership operator to assign values to individual fields:
benifit of using this is bits4 can hold only 16 values i.e 0-15.
that I want to do in my new data type Nibble.

--it compiles, though it may not be accurate to the definition of a Nibble.

Ya! I know it compiles, and runs!
but whatever the code I posted is not the complete code! it's only a part!
is there any way by which I am able to overload extraction >> operator without
that error and without changing any part of code?

Thank you for your priceless time!
Any help

>>Now you can use the usual union membership operator to assign values to individual fields:

NO YOU CAN'T. The union is used to assign the same memory location to several different POD (Plain Old Data) type objects. All the objects in the union below occupy the same space, and the size of the union is the size of its largest member. Example:

union myunion
{
     int a;
     short b;
     long c;
     double d;
     char f[8];
};

Here is more information about unions.

c++ bit fields are completly different animal. Read this article for explaination about how to use them. You will normally want to put bit fields in a structure.


>>is there any way by which I am able to overload extraction >> operator without
that error and without changing any part of code?

No. You will have to change the code to provide an extraction operator for Nibble.

I have posted the answer yesterday but DaniWeb site discard it (why?).

You can't redefine >> operator for bit fields because of no such animal as a reference to bit field in C++ language.

Use intermediate int variable then assign it to the bit field - but it's not >> operator, of course.

In general bit fields are useless part of C (and C++) language (next to nothing).
Better get it out of your head and go on...

I have posted the answer yesterday but DaniWeb site discard it (why?).

My guess is that you forgot to hit the Submit Reply button. I have never seen someone's post just disappear without reason.

In general bit fields are useless part of C (and C++) language (next to nothing).
Better get it out of your head and go on...

Strongly disagree. Just because YOU have not used them (yet) doesn't mean others haven't.

1. May be so...

2. Alas, I have used bit fields over 30 years ago in C...

Of course, it was my opinion. Of course, tastes differ...

In general bit fields are useless part of C (and C++) language (next to nothing).
Better get it out of your head and go on...

2. Alas, I have used bit fields over 30 years ago in C...

So ... bit fields aren't useless aftersll :)

Some useful links (brief and clear texts) about unions:
http://www.cenapad.unicamp.br/parque/manuais/Ibmcxx/language/ref/rucldun.htm
and bit-fields:
http://www.cenapad.unicamp.br/parque/manuais/Ibmcxx/language/ref/rucldst.htm#decusebit

Some quotes on this topic:

The assembly generated for the bit-field structure is undoubtedly the largest and
slowest. These are the types of constructs that make C/C++ infamous for code-bloat. It is
twice as large and more than twice as slow as its peers. From inspection of the generated
assembly, it is clear that the C/C++ compiler generates a load/modify/store sequence for
every access of a bit group in the structure (Listing 24). It would be hard to be more
inefficient.

http://www.open-std.org/jtc1/sc22/wg21/docs/ESC_Boston_01_304_paper.pdf

A note of caution: Portability
Bit fields are a convenient way to express many difficult operations. However, bit fields
do suffer from a lack of portability between platforms:

integers may be signed or unsigned
Many compilers limit the maximum number of bits in the bit field to the size of an
integer which may be either 16-bit or 32-bit varieties.
Some bit field members are stored left to right others are stored right to left in
memory.
If bit fields too large, next bit field may be stored consecutively in memory
(overlapping the boundary between memory locations) or in the next word of memory.

http://www.cs.cf.ac.uk/Dave/C/node13.html

A compiler may pack consecutive bit-fields of a class, struct, or union into a single
addressable storage unit. However, the order of allocation of those bit-fields within
that storage unit is implementation-defined.
...
The Standard doesn't require compilers to allocate the first bit-field at one end or the
other. It simply says that the allocation order is implementation-defined. Other
allocation strategies are possible.
...
In researching this particular item, I discovered a small but interesting disparity
between C and C++ regarding bit-fields. Both the C and C++ Standards agree that the
allocation order for bit-fields is implementation-defined. But, while the C++ Standard
says the alignment of the storage unit holding the bit-fields is also
implementation-defined, the C Standard says it's unspecified.

Once again, implementation-defined and unspecified behaviors offer each compiler some
latitude in translating programs. The upside of this freedom is that it allows each
compiler to translate these constructs into code that's most efficient on the target
platform. The downside is that it can create portability problems. Code that yields
correct results on one platform may produce surprisingly different results when compiled
and executed on other platforms.

http://www.embedded.com/9900563

So then with bit-fields we (may be;)) have "clear", but (most likely) unportable and (known to be) inefficient codes. Probably, in real-time and/or multi-threading environments it has unpredictable behaviour. Never mind, it's nothing!..

What's a wonderful construct ;)...

Thanx for your answers guys!
BUT STILL ALL THESE Replies ARE NOT helping me to understand, how '<<' insertion operator works with bit field and why not with '>>' extraction operator!
please help!
thanksss

>>BUT STILL ALL THESE Replies ARE NOT helping me
BECAUSE YOU ARE NOT LISTENING!

Here is an example how to do it.

#include <fstream>
using namespace std;


union myunion
{
    unsigned int x;
    struct mystruct
    {
        unsigned int bit1:1;
        unsigned int bit3:1;
        unsigned int bit4:1;
        unsigned int bit5:1;
        unsigned int bit6:1;
        unsigned int bit7:1;
        unsigned int bit8: 1;
    }x2;
};

int main()
{
    myunion u;
    u.x = 123;
    ofstream out("data.txt");
    out << u.x;
    out.close();
    ifstream in("data.txt");
    int >> u.x;
    in.close();
}

>>BUT STILL ALL THESE Replies ARE NOT helping me
BECAUSE YOU ARE NOT LISTENING!

Here is an example how to do it.

#include <fstream>
using namespace std;


union myunion
{
    unsigned int x;
    struct mystruct
    {
        unsigned int bit1:1;
        unsigned int bit3:1;
        unsigned int bit4:1;
        unsigned int bit5:1;
        unsigned int bit6:1;
        unsigned int bit7:1;
        unsigned int bit8: 1;
    }x2;
};

int main()
{
    myunion u;
    u.x = 123;
    ofstream out("data.txt");
    out << u.x;
    out.close();
    ifstream in("data.txt");
    int >> u.x;
    in.close();
}

Wow, I think I understood that!

Because the entire union shares memory across all of the data inside it, when assigning a value to an int, you can then access the bit through the bitmasks because they reside in the same memory location, but aren't the size of the int (so in a sense you're getting a small chunk of the int via bitmasks).

Is this a good way of looking at it?

Edit: I think you forgot bit2 >_>

The code I posed only accesses 8 of the int's 32 bits (assuming 32-it compiler).

Ah, so then if C++ really wanted a defined "byte" type, it could be implemented in this way?

#include <iostream>

// allows range of 00000000 to 11111111
union byte{
    int num;
    struct{
        unsigned int zero:  1;
        unsigned int one:   1;
        unsigned int two:   1;
        unsigned int three: 1;
        unsigned int four:  1;
        unsigned int five:  1;
        unsigned int six:   1;
        unsigned int seven: 1;
    };

    byte(unsigned short value){
        num = (value >= 0) ? ((value < 256) ? value: 255) : 0;
    }

    byte(byte &other){
        num = other.num;
    }

    unsigned short operator=(unsigned short value){
        num = (value >= 0) ? ((value < 256) ? value: 255) : 0;
        return num;
    }

    unsigned short operator=(byte &other){
        num = other.num;
        return num;
    }

    friend std::ostream& operator<<(std::ostream& os, byte& value);
};

std::ostream& operator<<(std::ostream& os, byte& value){
    os << value.seven << value.six << value.five << value.four << value.three;
    os << value.two << value.one << value.zero;
    return os;
}

int main(){
    byte b = 123;
    std::cout << b << std::endl;
    std::cin.get();
    return 0;
}

Edited**

In general, answer negative.

A mapping of zero..seven bit fileld to a byte (to bits of num member in your case) is implementation-defined. Of course, it's possible to make experiments, but one morning (evening, night), when you install the great new C++ compiler...

You know, I thought I had responded to this thread yesterday, but now I remember I was called away before I could finish typing.

'Bitfields', in the sense of using individual bits in an integer value, are very useful.

'Bitfields', in the sense of the C++ foo:1; syntax, have a very limited use. That is because the standard inexplicably fails to define the order in which the bitfields are to be packed. Hence, you just don't know. Using them is only useful when they are managed abstractly and when they are explicitly tallied when reading and writing to file (or anything else: integers or video memory or whatever).


However, I don't think anyone has addressed the original design problem. While having a 'nibble' class would be cool, it is impractical. The basic problem is that the smallest unit of reference (in most modern computers) is the byte: eight bits together. It is true that you can manipulate individual bits, but they don't stand alone. Each bit is always associated with a minimum of seven other bits. Thus, a single nibble is convenient until you have to use it somewhere.

Trying to read and write a nibble from file illustrates the problem quite nicely. You have to read or write at least two nibbles at a time. So what do you do with the second nibble? You probably don't want to just throw it away.

What I would recommend instead of a nibble class is a stream class that can give you a specific number of bits at a time. That way it can manage the actual state of the data and provide access to individual nibbles (or any other range of bits).

The other option, while not as cool, but much easier to do, would be to make a function or class with static data to read and write bytes to/from a file and dispense N bits as desired. This would depend on the file not being modified too heavily between calls to the function/object (in general, just leaving it alone while the "nibbler" is in use is a good idea).

If you need help making sense of my babblings feel free to ask for more info.

Thanx all of you!
specially thanks to DaniWeb site!
I think All Intelligent Brats are here!

Thanx all of you!
specially thanks to DaniWeb site!
I think All Intelligent Brats are here!

Was it really appropriate to label us as brats? =/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.