PDA

View Full Version : OOP - memory and class methods


-Vormav-
06-02-2006, 10:06 AM
Just want to try and clear up one issue with OOP that I'm not completely sure of: methods.
Let's say I've developed a base class that implements a special error reporting method. When I create a new object from this class, it obviously has access to the error reporting method. Simple enough. But what if I create multiple objects from the same class? Are they all accessing the same method stored in the same memory space, or do they have their own separate instances of that error reporting method stored in separate memory spaces (thus taking up more memory)?

Seems like it would definitely have to be the former, but just want to make sure I have a correct understanding of what's going on.

relief7
06-02-2006, 12:45 PM
Your first assumption is right. Each class has its own table of functions but this table is shared by all objects of that class. Memory is reserved only for the member variables used by the different instances.

For a detailed reference check out Bjarne Stroustrups book "The C++ Programming Language".

gga
06-03-2006, 09:50 AM
When I create a new object from this class, it obviously has access to the error reporting method. Simple enough. But what if I create multiple objects from the same class? Are they all accessing the same method stored in the same memory space,

Yes.



or do they have their own separate instances of that error reporting method stored in separate memory spaces (thus taking up more memory)?

The actual methods are not duplicated. But the class data is.
An example:


class MyClass
{
public:
// constructors/destructors omitted...
void report() {
// does something... say with val[]
};

protected:
int val[256];
};

int main()
{
MyClass x, y;
return(0);
}



In the example above, x and y share the same member function called report() which resides in a single place in memory.
However, x and y do use each one more memory for their int val[] array data and report() could operate on that data, independently.

-Vormav-
06-05-2006, 08:24 AM
Sweet. Thanks for clarifying. :)

Robert Bateman
06-05-2006, 03:31 PM
Are they all accessing the same method stored in the same memory space, or do they have their own separate instances of that error reporting method stored in separate memory spaces (thus taking up more memory)?

Sort of in the same memory, but not quite. Recursion will duplicate the data required for the function on the stack, but it's not worth worrying about. FYI, the rules are basically the same for member functions as normal functions.

CGTalk Moderation
06-05-2006, 03:31 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.