Link to home
Start Free TrialLog in
Avatar of Frost_Byte
Frost_ByteFlag for Israel

asked on

Class functions and memory

This is a simple one but ...:
I'd like to know once and for all, if I have a class with several member functions (just regular functions). If I create several objects of that class, I know the data members are duplicated for each object (memory is allocated for each var, in each object), but, are the functions _themselves_ duplicated as well ? Is every object taking up space for both it's data AND it's functions ? If so, how can I avoid this ?
Thanks
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nietod
nietod

Member functions appear to be part of an object because they are accessed with the same syntax used to access data member.  However functions are not stored with the objects.  (This actually would be implimentation defined, that is, someone could write a C++ compiler that did store the functions with the objects.  However, I can pretty much guarantee that it has never and will never be done!)
Note that if a class is publically derived from a base class, the public functions of the base class can also be used on objects of the derived class.  Again this would be implimentation defined, but I would bet that no implimentations ever written would provide seperate copies of the function for the base and derived class.  

Also note that static data members are not stored in objects of the class.  If a class has a static data member, only one copy of that data member exists and is shared by all the objects that are part of the class.
One missed detail:

Generally, an object of a class with no non-static data members will take no memory.
However, if the class defines *virtual functions*, the object will contain a pointer to the vtable.  Similarly, objects of a class with *virtual inheritance* will contain pointers to the virtual base part.

OK, Todd, find your way out of this one :-)
>> Generally, an object of a class with no non-static data members will take no memory.
The objects won't need any memory, but they will have it.  Objects are forbidden to be 0 bytes long.

As for the virtual table pointer, that is the point.  rather than storing seperate functions for each object (which could be done to impliment virtual functions) it stores a single virtual table pointer.  rather than copies of the functions.

As for "virtual inheritance" I'm not sure how that fits into this, but that's okay because when I think about multiple inheritance my head hurts anyways.
If this has answered your question, you should grade it.
Avatar of Frost_Byte

ASKER

Sorry for the delay - my service provider was down...