Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The effect of class member function number

Tags:

c++

My question is related to C++ class definition. I understand that if there are many member variables existing in the class. The size of the class will increase. Increasing the number of class member functions, however, will not affect its size. However, I was wondering what is the major difference between a class with more member functions and a class with less member functions. Will it be possible that invoking a class with less member functions is much faster?

like image 251
feelfree Avatar asked Feb 19 '23 15:02

feelfree


1 Answers

You need per-instance space to store member variables, but member functions are not part of an instance, at least not directly. There is usually a single extra pointer that is required for each additional virtual member function, but that pointer goes to vtable which is shared among all instances of a class, and therefore does not add to per-member size.

Non-virtual member functions take space only in the code memory: their space requirements are no different from free-standing functions, the only difference being the hidden parameter for passing the pointer to this.

The first virtual function added to a class adds an extra pointer to the space required to store an instance; additional non-virtual member functions do not play into space requirements at all.

like image 129
Sergey Kalinichenko Avatar answered Mar 05 '23 06:03

Sergey Kalinichenko