C ++ RTTI Inheritance increases class size

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 more than one byte if A is part of B, when I do sizeof (B) and an object of type B. A will 100% only include non-virtual members (no virtual table required) and no the need for type checking. Is there a way (like a compiler directive) to completely remove the unnecessary byte from B, but still access the member function through B?

I can only assume that the extra byte is the compiler appended char * to the name "A", but any other ideas might be helpful.

0


a source to share


2 answers


sizeof (A) cannot be 0 because every part of the object must be "addressable" (that is, if we use the & 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" 
}

      

+4


a source


Unfortunately you don't mention compilers.

In any case, in the code you are posting, class A is a candidate for "Empty Base Class Optimization". Which is part of the C ++ standard, which says that a base class with no member variables can be optimized to not accept bytes.



B must take place by the C ++ standard since it contains at least one element (namely obj_A).

You can access the member function directly from within B by calling do_something (). No magic required.

+2


a source







All Articles