Search code examples
javac++memoryvirtual

Virtual methods memory usage Java vs C++


WARNING: Please keep in mind that this question is plain wrong - it makes a wrong assumption because I have misinterpreted a poorly written tutorial (a book actually) on C++. For case you are curious, this is the original contents:

In C++ marking a method as virtual causes the objects to use more memory - for every additional virtual method the memory for a pointer (4 - 8 bytes) more. How does Java deals with this, where all methods by default are virtual?


Solution

  • 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