Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Do functions within structs get copied with the struct?

In a struct (or class), I know that I can add a function and then call it later.

struct State {
    int turnsLeft;
    void nextTurn() {
        turnsLeft--;
    }
};
State s1{1};
State s2{2};
s1.nextTurn();

My question is, how do these functions relate to how much space the struct takes up? I know a int is 4 bytes and so creating s1 and s2 costs at least 4*2=8 bytes. But, will a new copy of this function be created each time that I make a new struct, or will only one copy of the function be made and shared no matter how many different State functions I make? If the function is copied each time, how can I write the code so that only one copy of the function is made? A static function doesn't work very naturally, since I want to access this when I modify turnsLeft.

like image 895
Alex Li Avatar asked Mar 19 '26 22:03

Alex Li


1 Answers

I suppose I need to start with a disclaimer: what I say below applies to all known implementations. In theory somebody could to things differently (but in this case it's so unlikely that it's hardly worth considering even as an intellectual exercise).

Member functions will only affect the size of the class in one way: if the class contains at least one virtual function, the size of the class will increase by the size of one pointer (usually called the vtable pointer). Even if the class doesn't directly define any virtual functions, if it inherits from a base class that declares at least on virtual function, it will have a vtable pointer for that class. If it inherits from multiple base classes, it will normally contain a vtable pointer for each base class that declares at least one virtual function. Using virtual inheritance can reduce that in a few specific cases.

But no, an object of a class doesn't normally "contain" actual copies of the function(s) of that class, so the size, complexity or number of normal member functions won't affect the size or time taken to copy an object of that class. Virtual functions can have some effect, but it's still usually pretty minimal.

Member functions do affect one other thing a bit though: non-static member functions have access to the data in the object on which they're invoked. Inside the member function, a pointer to that object is visible as this. In most implementations, even though it's not a visible parameter, this is actually passed as a parameter, so if you look at the generated code, it will contain an instruction or two to load this into some known location before the call is made. But this only affects the size of code calling a member function, not the size of the object of that class.

like image 185
Jerry Coffin Avatar answered Mar 22 '26 14:03

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!