New Student
New Student

Reputation: 167

When can an object have either but not both of non zero size , one or more bytes of storage?

C++ 14 intro.cpp States:

a most derived object shall have a non-zero size and shall occupy one or more bytes of storage

Why did they have to state

non-zero size

and

one or more bytes of storage

When can it have one but not the other ?

Upvotes: 6

Views: 164

Answers (2)

duong_dajgja
duong_dajgja

Reputation: 4276

There are cases in which a class may have a non-zero size (returned by sizeof) but it does not actually occupy any space on memory. For example, Empty Base Optimization (EBO) is used to make a base part of a derived object occupies no space on memory as shown in example below:

#include <stdio.h>

struct Base {};

struct Derived : Base
{
    int a;
};

int main()
{
    printf("sizeof(Base) = %d\n", sizeof(Base));

    Derived* p = new Derived;
    void* p1 = p;
    void* p2 = &p->a;

    if(p1 == p2) { printf("Good compiler\n"); }

    return 0;
}

Compiled with gcc 4.8.4 on Ubuntu 14.04 x64.

Output:

sizeof(Base) = 1
Good compiler

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409422

The two parts are actually saying different things.

a most derived object shall have a non-zero size

That means sizeof using an object will return a non-zero size.

a most derived object ... shall occupy one or more bytes of storage

That means the object occupies some bytes (one or more) of memory.

If the second statement didn't exist then that could mean that sizeof would report a non-zero size but the object might not actually use any memory.

Without the first statement it could mean that sizeof could return zero but the object would still take up space in memory.

Both are needed and orthogonal to each other.

Upvotes: 4

Related Questions