Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What determines object size here?

Tags:

c++

sizeof

I have created simple object containing integer and few methods, integer primitive variable alone and compare their sizes. "sizeof()" for both returned value of "4". Why is that - shouldn't object that is composite type and contains information about methods take more space?

#include <iostream>

class Person{

    private:
        int a;

    public:

        void hello(){
            std::cout << "hello";
        }

        void DoSomething(){
            a++;
        }
};

int main(){

    int a;
    Person p;

    std::cout << sizeof(a) << std::endl;

    std::cout << sizeof(p) << std::endl;

    return 0;
}
like image 303
ligik76 Avatar asked Dec 25 '22 22:12

ligik76


1 Answers

The methods (technically member functions in C++ terminology) do not contribute to the "size" of an object. If you think about it, it makes sense. A member function is applicable to any object instantiated from the class or its descendants, and is in a sense independent of the instance. You can think of the member function of some fictive class Foo as being a standalone function declared as

return_type some_member_function(Foo* ptr, /* other params */){...}

where the first parameter is a pointer to the instance you are applying the function to. The compiler actually passes the pointer ptr implicitly when calling the member function, so

foo.some_member_function(/* other params */)

is being translated internally as

some_member_function(&foo, /* other params */)

You can use the address of the current instance pointed by ptr in actual C++ code via the keyword this. Technically the keyword this is a prvalue expression whose value is the address of the object, on which the member function is being called.


PS: as @greyfade mentioned in the comment, the size of an object may be increased by a mere declaration of virtual member function(s), since in this case the compiler must store internally a pointer to the so called "virtual table". This is the case no matter if the virtual function is being overridden or not. So, if you care about object size, don't blindly make the destructor virtual, unless you plan to use your class as the base in a hierarchy.

like image 157
vsoftco Avatar answered Dec 28 '22 22:12

vsoftco