Sign in to follow this  
vesoljc

int bFlag : 1

Recommended Posts

afaik defining bit flags be also be used like:
class a {
protected:
   int     bFlag1       : 1;
   int     bFlag2       : 1;
};

and compiler will pack them. now i'm wondering if this works for inheritance also? like:
class b: public a {
protected:
   int     bFlag3       : 1;
   int     bFlag4       : 1;
};

will these flags share "same" memory or not?

Share this post


Link to post
Share on other sites
Depends on the compiler. AFAIK, the standard says they don't need to (Since they're not in the same class/struct), but I can't see any reason why a good compiler couldn't pack them.

Easy way to test: What's sizeof(b) in the above case?

Share this post


Link to post
Share on other sites

#include <iostream>
struct A
{
int bFlag1 : 1;
int bFlag2 : 1;
};

struct B : A
{
int bFlag3 : 1;
int bFlag4 : 1;
};

int main()
{
std::cout << sizeof(B);
}



This little program gives an output of 8 of VC6 and VS2003.Net. I don't have access to any other compilers ATM.

Share this post


Link to post
Share on other sites
So it looks like most compilers don't perform this optimization. Can't say I'm suprised - bit fields aren't used that much, and it could be faked with bitwise operations if it were really important.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this