Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

c++ - Do class methods increase the size of the class instances?

The question is pretty straight forward. For clarity, consider the example below:

// Note that none of the class have any data members
// Or if they do have data members, they're of equal size, type, and quantity
class Foo {
public:
    void foo1();
    void foo2();
    // 96 other methods ...
    void foo99();
};

class Bar {
public:
    // Only one method
    void bar();
};

class Derived1 : public Foo { };
class Derived2 : public Bar { };

int main() {
    Foo f;
    Bar b;
    Derived1 d1;
    Derived2 d2;
    return 0;
}

Do instances f, b, d1, and d2 all occupy the same amount of space in memory? As an extension to this question, would copying instances of Foo when passing it around take longer than Bar, theoretically?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Only instance data increases the size of instances of a class (in all implementations that I know of), except that if you add virtual functions or inherit from a class with virtual functions then you take a one-time hit for a v-table pointer.

Also, as someone else correctly mentions the minimum size of a class is 1 byte.

Some examples:

// size 1 byte (at least)
class cls1
{
};

// size 1 byte (at least)
class cls2
{
    // no hit to the instance size, the function address is used directly by calling code.
    int instanceFunc();
};

// sizeof(void*) (at least, for the v-table)
class cls3
{
    // These functions are indirectly called via the v-table, a pointer to which must be stored in each instance.
    virtual int vFunc1();
    // ...
    virtual int vFunc99();
};

// sizeof(int) (minimum, but typical)
class cls4
{
    int data;
};

// sizeof(void*) for the v-table (typical) since the base class has virtual members.
class cls5 : public cls3
{
};

Compiler implementations may handle multiple virtual inheritance with multiple v-table pointers or other other methods, so these too will have effect on the class size.

Finally, member data alignment options can have an impact. The compiler may have some option or #pragma to specify that member data should have a starting address that is a multiple of the number of bytes specified. For example, with alignment on 4 byte boundaries and assuming sizeof(int) = 4:

// 12 bytes since the offset of c must be at least 4 bytes from the offset of b. (assuming sizeof(int) = 4, sizeof(bool) = 1)
class cls6
{
    int a;
    bool b;
    int c;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...