Solved

Member functions

Posted on 2004-04-05
19
249 Views
Last Modified: 2010-04-01
 The size of a c++ object is independent of the number of member functions. why ?
0
Comment
Question by:a_nicet
  • 3
  • 3
  • 3
  • +6
19 Comments
 
LVL 16

Expert Comment

by:nonubik
ID: 10756171
because they are in some virtual function table
0
 
LVL 16

Expert Comment

by:nonubik
ID: 10756180
0
 
LVL 16

Accepted Solution

by:
nonubik earned 50 total points
ID: 10756197
0
 
LVL 12

Assisted Solution

by:stefan73
stefan73 earned 50 total points
ID: 10756232
Hi a_nicet,
the member functions "belong" to the class, not to each instance.

Some other OO (or OO-like) languages, such as Lua, allow each instance to have different functions, as functions are first-class variables, and you can add any value to an instance (a table in the Lua case). C++ offers no such feature. If we have to be grateful for that is left open to the reader :-)

Cheers,
Stefan
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 10756600
Just so you know (you probably already do anyway), the size of an object is equal to the sum of the sizes of its variables.  This has probably already been mentioned in one of the links posted above, but I did not read both fully :)
0
 
LVL 14

Expert Comment

by:wayside
ID: 10756646
Non-virtual member function usage is determined at compile time, and therefore there is no need for the object to carry the overhead of a function table. Adding more functions does not increase the object size.

If you have virtual functions, which function gets called gets determined at run-time, and the object maintains a table of function pointers to figure this out. In this case, the size of the object will increase as virtual functions are added because each new virtual function requires an entry in the function table.
0
 
LVL 2

Assisted Solution

by:guntherothk
guntherothk earned 50 total points
ID: 10758591
The non-virtual member function void Foo::f() is compiled as if it was an extern c function

void Foo_f(Foo* const this)

The address of this function isn't dependent on the class instance, so it doesn't change the size of the class instance. You can have as many non virtual functions as you want, and it doesn't affect the size of the instance.

If the function was virtual void Foo::f(), the call looks kinda like

pFoo->_vtable[F$address](pFoo)

where pFoo is a pointer to Foo, _vtable is a pointer to an array of function pointers that is a member of every instance of Foo, and F$address is an offset within the virtual function table that contains a pointer to f.

So adding the first virtual function to a class does make every instance bugger, because every instance will have a pointer to the virtual function table. However, adding additional virtual functions only increases the size of the vtable, not the vtable pointer in each instance.
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10764103
guntherothk,
> adding additional virtual functions only increases the size of the
> vtable, not the vtable pointer in each instance

Exactly. As instances of a class should have the very same methods, they share the very same virtual table.

Stefan
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 2

Assisted Solution

by:bronkbronk
bronkbronk earned 50 total points
ID: 10764219

A slight note of caution in relation to a previous note: don't count on the size of an object to be the sum of the sizes of its member variables. More member variables mean larger object size, but due to compiler and platform specifics you cannot in the general case simply add the individual member variable sizes.

Also note that using RTTI will require the existence of virtual tables for each class hierarchy where RTTI is applied, thus possibly leading to increased object size. However, as noted above, there will still not be any relation between the number of member functions and the object size.

Regs,
Bronk
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 10764335
bronkbronk:

>> "due to compiler and platform specifics"

Does this refer to sizeof(int) on one platform not being the same as it is on others ?  Or are there more intricate compiler details that you would like to go into ?

0
 
LVL 2

Expert Comment

by:bronkbronk
ID: 10764624
One problem is alignment, i.e. the requirement on the address of data to be a multiple of a specific value (e.g., a multiple of 4 bytes on a 32 bit machine using an ordinary compiler). Try checking the size of these three classes on your favorite compiler:

class A { char c };
class B { int i; };
class C { char c; int i; };

Chances are you get something like 1(sic!), 4, and 8. The last case is because introducing the integer member also forces adaptation to the platform specific alignment for the entire class.

Regards,
Bronk
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 10764956
bronkbronk:

Interesting stuff.  Many thanks !
0
 

Author Comment

by:a_nicet
ID: 10765133
The question  has no relation with the virtual functions and no vptr.  
like
class A { };   // Size of class is 1 bcoz 1 byte is an identity..
class B{ Print() {}; };  // The size is X
class C{PrintA() { };  Printb() { } ; };  // The size is X
if so where is memory for function is allocated.. How does the object knows that such function is calling ??
0
 
LVL 8

Assisted Solution

by:mxjijo
mxjijo earned 50 total points
ID: 10769773
a_nicet ,
    I guess your question is : why does size of the function body is *not* counted while calculating the size of the object. The answer is - that is the logic. The whole concept behind object oriented programming is to isolate data from functions. In other words data is data, not matter how many functions defined on it. For example say you are defining an apple. You can do so many things on it - cut, peal, eat .. etc etc.. But, the concept "apple" remains the same. While buying an apple we pay only for the weight of the apple, not for all "other" things that you may do on it.

    The same way, all methods (member functions) you define in an object *do* consume memory one way or the other !!, however, when someone asks for the size of the object (sizeof(your_object)) we count only the size of the member variables and *not* number of bytes occupied by the functions.

   So, in short, that is the concept :)
~ j
0
 
LVL 2

Expert Comment

by:bronkbronk
ID: 10772781
a_nicet,

There is a difference between classes and objects. Each class can define its own set of functions. This code is common to all objects of that class. The code is stored in your executable file. When starting the program the executable code is atored in memory.

During execution, you can create any number of objects. Creating an object means allocating memory for holding the objects own data. However, there is no need to duplicate any code to be executed, but only a reference to (i.e., the position in memory of) the code to code is associated with the object. In many cases, the relationship between an object and the code to be executed is resolved during compilation, and does thus not impact the size of the object. When using virtual functions, this is not the case, and thus each individual object having at least one virtual function will need to hold a reference to a virtual table. One and the same virtual table is however shared by all objects of the same class.

Let's look at your example above:

class A { };   // Size of class is 1 bcoz 1 byte is an identity..
class B{ Print() {}; };  // The size is X
class C{PrintA() { };  Printb() { } ; };  // The size is X

The classes B and C specify some code common to all objects of those classes. However, when instantiating an object of class B or class C, there is no need to duplicate the code for each object, but all objects execute the same code. Since neither of A, B or C has any object data nor any virtual functions, objects of all these classes should have the same size, i.e. 1.

You can also try to checking the sizes of the below classes:

class A { int i; };
class B { int i; void foo() {} };
class C { int i; virtual void foo() {} };

On a 32-bit machine you will likely get sizeof(A)=sizeof(B)=4 and sizeof(C)=2*sizeof(A)=8. Note that sizeof(AClass) returns the size of objects of the class, not the size of the code and data of class itself.

Thus, for
A m1;
B m2;
C m3;

you will get
sizeof(A) == sizeof(m1)
sizeof(B) == sizeof(m2)
sizeof(C) == sizeof(m3)

On a barely related issue, note that running sizeof on polymorphic objects can give you sursprising result;

class D : public C
{
  char c;
};
C* ptr = new D();

Will yield
sizeof(D) != sizeof(*ptr)


Regards,
/Bronk
0
 
LVL 9

Expert Comment

by:jasonclarke
ID: 10789790
> sizeof on polymorphic objects can give you sursprising result;

not really surprising, sizeof only looks at the static type of an object.  The static type of *ptr is 'C' so sizeof(*ptr) will always return the sizeof(C), regardless of whatever *ptr actually points at.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now