102 posts
Function inside struct/class vs outside
Edited by C_Worm on Reason: Initial post
let's say we have this struct:

  1 2 3 4 5 6 7 8 9 10 11 12 struct Unit { int x; int y; void Move(int mov_x, int mov_y) { x += mov_x; y += mov_y; } }; 

And this stand alone function:

 1 2 3 4 5 void Move(Unit *u, int mov_x, int mov_y) { u->x += mov_x; u->y += mov_y; } 

And pretend that we create like 500 units in a game.

If i'm not mistaken this would result in the Unit beeing more memory expensive since every Unit will have the move function instead of just have one stand alone function that moves Units.

Does it make sence?

And what are you thoughts on splitting functions inside/outside structs/classes, what kind of functions would be good to have inside structs and which would be better to have outside.

I got bugged by this thought and would like to here some opinions on this.

cheers :)

Mārtiņš Možeiko
2378 posts / 2 projects
Function inside struct/class vs outside
Edited by Mārtiņš Možeiko on
When you say "every Unit will have the move function", do you think Unit structure is different whether it has inline function or not?
Because that does not matter at all. class/structure member function does not change size of structures at all (except virtual functions).
Conceptually they are same as global "standalone" function - only thing it affects is syntactic scope. Compiler expects function to be in Unit:: scope, not :: global one. And it has implicit first argument this which is Unit* - so from runtime perspective it is exactly same as your global Unit function.
102 posts
Function inside struct/class vs outside
Allright, thanks for clearing that out for me! :)