How are class functions stored in memory?

1
2
3
4
5
class MyClass{
    int x;
public:
    int GetX{return x;}
};


Questions:
1. If I make ten class MyClass objects, does it store ten copies of the int GetX function in memory?
2. If I make int GetX a friend function instead, how many copies does it store in memory then?

Right now, I have a class that calls a function outside of itself. It's not as clean, but doing it that way, I'm sure that that function is stored only once in memory instead of once for each instance of that class. However, I'd like to put that function and those like it into the class if it's not going to eat up more memory.

Off-topic: Is that last semi-colon necessary?
Last edited on
1) No, class functions are basically a special case of normal functions that take an implicit this parameter.

2) 1, as always.

3) Yes
Chemical Engineer wrote:
If I make ten MyClass objects, does it store ten copies of the GetX function in memory?

No. It only stores one.

Chemical Engineer wrote:
If I make GetX a friend function instead, how many copies does it store in memory then?

Again, one.

Chemical Engineer wrote:
Off-topic: Is that last semi-colon necessary?

Yes. My guess is that they made it that way to allow this:

1
2
3
4
5
class MyClass{
    int x;
public:
    int GetX{return x;}
} my_object1, my_object2;
Awesome, thanks guys.
Topic archived. No new replies allowed.