views:

622

answers:

2

In C++ the problem is simple.

I have 2 classes one contains the other as part of its implementation.

struct A
{
    void do_something()
    {
    };
};

struct B
{
    A obj_A;
    void hello_world()
    {
    };
};

Now the problem is that structure B is one byte larger if A is part of B when I do a sizeof(B) and object of type B. A is 100% only going to include only non-virtual members (no virtual table required) and there is no need for a typeid check. Is there any way (like a compiler directive) to completely remove the unneeded byte from B but still access A's member function through B?

I can only assume the extra byte is a compiler added char* to A's name "A" but any other ideas can be helpful.

+1  A: 

You don't mention compilers, unfortunately.

Anyway, in the code you post, the class A is a candidate for the "Empty Base Class Optimization". Which is a part of the C++ standard that says that a base class with no member variables can be optimized away to take up no bytes.

B must by the C++ standard take up space, as it contains at least one member (namely obj_A).

You can access A's member function directly from within B, by calling do_something(). No magic is needed.

Macker
Is class A really considered a base class?
Rob Kennedy
Yes, it it is also a leaf class
1800 INFORMATION
It may be a base class, but not B's base class.
Ari
+3  A: 

sizeof(A) cannot be 0 because, each part of an object should be "adressable" (that is should have a different adress when we use operator &)

struct A
{
};

struct B
{
    A m_a1;
    A m_a2;
};

void test()
{
    B b;
    A* pa1 = &b.m_a1;
    A* pa2 = &b.m_a2;

    // "pa1" need to be different from "pa2" 
}
Rexxar
+1 Thats right. Also, every new of the class should return a different address so that use of delete will work properly. Thats the reason classes in C++ cannot have size = 0. Apart from this there are aspects of padding that a compiler may add to make the object align to the memory-word boundary.
Abhay