0

In C++, if I define a function like below

int func1(int a, int b){ 
  int res;
  // do some stuff for a, b, res;
  return res;
}

I know there will be only one copy of machine code for func1 generated by the compiler if it is not inlined (correct me if I am wrong), and during program execution every call for func1 will call that copy of machine code. However, for member functions in class, like below

 class A{
 private:
    // some data members and member functions
 public: // or alternatively private: 
    int func2(int a, int b){ 
      int res;
      // do some stuff for a, b, res;
      return res;
    }
 }

I have some questions as below:

  1. If I do sizeof(A), it only returns the size of the data members (possibly including padding bytes), then where func2 is stored? Is func2 stored in a piece of memory continuous with the data members? If not, doesn't it penalize caching?
  2. If I declare std::vector<A> v(1000), will there be 1000 copies of machine code for func2 generated? If yes, I think this will result in a big memory wastage and performance disadvantage compared to declaring functions outside the class like func1(correct me if I am wrong).
Allanqunzi
  • 3,230
  • 1
  • 26
  • 58

1 Answers1

1

In C++, class member functions are implemented in essentially the same way as regular C-style functions. However, they have a "secret" first argument which is the this pointer, to the instance of the class on which the method was called. Thus, there is only one copy of the class member function instantiated either.

(There are some potential issues about multiple compilation units and linkage... but since you ignored them in the question we'll keep ignoring them now for convenience.)

If you want to see for yourself, you can take pointers to the member functions of various instances of a class, and compare them to see if they are equal or not.

Chris Beck
  • 15,614
  • 4
  • 51
  • 87
  • Thanks. You mentioned something about multiple compilation and linkage, do you know where I can find some materials to read about them? Thanks again. – Allanqunzi Sep 07 '15 at 03:21