简体   繁体   中英

When is the memory space for a member function of a class in C++ allocated?

While reading I read these conflicting statements on the memory allocation of member functions of Classes in C++. One source said the space is allocated for the member functions as on need basis from the memory stack. While the other said the space is allocated when the first object of that class is created.

On the other hand, I had the notion that space for member functions are allocated during compilation or beginning of runtime itself, and the function code is then used by all the objects of that class.

Could someone please clarify and elaborate? Thanks.

What memory? There's memory needed to store the actual (compiled code) and memory for the variables (Data). Both your answers are therefore correct.

Member functions does not contribute to the memory usage of class objects except that if a class has virtual functions then it keeps a pointer to the table of virtual functions.

As any function a member function can have no definition if there is no access to the function in the program. Otherwise the linker will issue an error that the reference to the function is undefined.

The compiler generates code for member functions the same way as for non-member functions. So if there is a definition of a member function when the compiler will generate the corresponding code.

I think that you meant member functions of template classes then they indeed will be instantiated if they are used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM