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:
- If I do
sizeof(A)
, it only returns the size of the data members (possibly including padding bytes), then wherefunc2
is stored? Isfunc2
stored in a piece of memory continuous with the data members? If not, doesn't it penalize caching? - If I declare
std::vector<A> v(1000)
, will there be 1000 copies of machine code forfunc2
generated? If yes, I think this will result in a big memory wastage and performance disadvantage compared to declaring functions outside the class likefunc1
(correct me if I am wrong).