Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you determine the size of an object in C++?

For example, say I have a class Temp:

class Temp {     public:         int function1(int foo) { return 1; }         void function2(int bar) { foobar = bar; }      private:         int foobar; }; 

When I create an object of class Temp, how would I calculate how much space it needs, and how is it represented in memory (e.g.| 4 bytes for foobar| 8 bytes for function1 | etc | )

like image 315
Joel Avatar asked Jun 02 '09 03:06

Joel


People also ask

How do you find the size of the object of the class?

One way to get an estimate of an object's size in Java is to use getObjectSize(Object) method of the Instrumentation interface introduced in Java 5. As we could see in Javadoc documentation, the method provides “implementation-specific approximation” of the specified object's size.

Which operator can be used to check the size of an object?

Which operator can be used to check the size of an object? Explanation: The sizeof operator is used to get the size of an already created object. This operator must constail keyword sizeof(objectName). The output will give the number of bytes acquired by a single object of some class.

What is the size of object of a class in C++?

In C++, the Size of an empty structure/class is one byte as to call a function at least empty structure/class should have some size (minimum 1 byte is required ) i.e. one byte to make them distinguishable.


1 Answers

To a first order approximation, the size of an object is the sum of the sizes of its constituent data members. You can be sure it will never be smaller than this.

More precisely, the compiler is entitled to insert padding space between data members to ensure that each data member meets the alignment requirements of the platform. Some platforms are very strict about alignment, while others (x86) are more forgiving, but will perform significantly better with proper alignment. So, even the compiler optimization setting can affect the object size.

Inheritance and virtual functions add an additional complication. As others have said, the member functions of your class themselves do not take up "per object" space, but the existence of virtual functions in that class's interface generally implies the existence of a virtual table, essentially a lookup table of function pointers used to dynamically resolve the proper function implementation to call at runtime. The virtual table (vtbl) is accessed generally via a pointer stored in each object.

Derived class objects also include all data members of their base classes.

Finally, access specifiers (public, private, protected) grant the compiler certain leeway with packing of data members.

The short answer is that sizeof(myObj) or sizeof(MyClass) will always tell you the proper size of an object, but its result is not always easy to predict.

like image 151
Drew Hall Avatar answered Sep 23 '22 20:09

Drew Hall