There is a certain class, 褋lass A_class; it has an int b; property int b; and void action(); method void action(); which contains some code.

So, what will happen if in several places of the code to create objects of this class in the amount of two or more such as A_class C; A_class D; A_class C; A_class D; Full copies of objects will be created?

The executable code of the action() method will also be stored twice? And if memory is allocated dynamically through new ? And how will the explicit constructor be stored in such cases? Will the compiler try to optimize the code and remove copies of the methods?

    1 answer 1

    Functions are not stored in objects. You can see for yourself by applying the sizeof operator to different classes with the same data fields and different numbers of functions. It doesn't matter how the object will be created: on the stack or on the heap through new . The code (function body) is stored in a single copy (I will not talk about inline yet).

    A non-static member function (method) differs from an ordinary free function only in that it implicitly has an additional parameter that refers to an object instance. Those. it does not affect the storage of the function code.

    The constructor in this regard is not any special and can be viewed as a normal function.

    • can proof if not difficult? - Dow Jhob
    • @DowJhob what exactly? - 伪位蔚蠂慰位蠀蟿
    • Well, where is it described in the standard - Dow Jhob
    • one
      @DowJhob I don鈥檛 think it is in the standard. Yes, and I would not recommend you to go there at all. Allocation of some code into a function sets itself the goal of eliminating duplication. Those. make a call instead of a substitution. If you are aware of this for a normal (free) function, you should understand for a member function after reading my answer. A little more complicated situation with virtual functions. Usually, for this, each object stores a pointer to a table of virtual functions. But this behavior is also not described in the standard and is given to specific implementations. - 伪位蔚蠂慰位蠀蟿