question

DenverCox-8894 avatar image
0 Votes"
DenverCox-8894 asked Viorel-1 commented

does creating a c++ class that contains methods create new instances of those methods?

Does creating a new instance of a class make new instances of every method within the class?
class example{ public: int x; void dosomething(){ x++; } };
would this make multiple instances of the 'dosomthing' function everytime a new instance of the class is created, or would it act like the code below.
class example{ int x; } void dosomething_not_in_class(example* e){ e->x++; }

c++
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

SimpleSamples avatar image
1 Vote"
SimpleSamples answered Viorel-1 commented

No, there would not be multiple instances. There would be only one copy of the method shared by all instances. Each instance gets its own stack for storing data local to that instance. Search for articles describing thread-safety and reentrancy; those topics are related to each other and to your question.

Related to that, for DLLs there is only one copy of a DLL in physical memory that is shared by all processes (applications also called address spaces) in the system using virtual storage.

· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.


It seems difficult to find articles about “Each instance gets its own stack…” and “there is only one copy of a DLL in physical memory that is shared by all processes”.

0 Votes 0 ·

Explanations of stacks are provided in most beginner books about programming. Beginner lessons about functions and methods explain the difference between stacks and heaps and explain that each execution of a function or method must have a stack. I assume that DenverCox-8894 does not need an explanation of stacks; I mentioned stacks to help explain that there is no need for more than one instance of the code.

0 Votes 0 ·

A couple of reasons why I did not provide details about DLLs is that it is not directly a part of the question and because it might add unnecessary confusion. c++ - Are .dll files loaded once for every program or once for all programs? - Stack Overflow explains what I mean about DLLs being loaded once into physical memory and mapped to all users (applications that use them). For an official statement see Memory Protection. Although when you read those you will see that sometimes a DLL must exist in more than one place in physical memory and you can read about that in those.


0 Votes 0 ·

Thank you for taking the time to give directions.

0 Votes 0 ·