[Solved] Virtual methods memory usage Java vs C++ [closed]


Your basic assumption is incorrect. The size of the object does not increase with the number of virtual functions.

If the class has ANY virtual functions then it has a single pointer to a vtable for that class. The size of the object won’t change beyond that regardless how many virtual functions:

struct s0 {};

struct s1
{
    virtual void f1() {}
};

struct s2
{
    virtual void f1() {}
    virtual void f2() {}
};

struct s3
{
    virtual void f1() {}
    virtual void f2() {}
    virtual void f3() {}
};

int main()
{
    std::cout << "s0: " << sizeof(s0) << '\n';
    std::cout << "s1: " << sizeof(s1) << '\n';
    std::cout << "s2: " << sizeof(s2) << '\n';
    std::cout << "s3: " << sizeof(s3) << '\n';
}

RESULTS:

s0: 1
s1: 8
s2: 8
s3: 8

1

solved Virtual methods memory usage Java vs C++ [closed]