1

Consider the following code:

#include <iostream>
using namespace std;
class item{
    int cost;
    float price;
    public:
    void getData(){
        cin>>cost;
        cin>>price;
    } 
};
int main(){
    cout << sizeof(item);
    return 0;
}

The output of this code is 8 bytes, as far as I understand it is 4 bytes for int and 4 bytes for float. Why does the sizeof operator not print the size of function, also how much and where is the memory allocated for function getData?

  • 3
    Functions are instantiated once and placed outside the actual data block. No matter how many instances of `item` you have, there will only be one `getData()` function in your program. – Ted Lyngmo Mar 08 '21 at 16:02
  • So if I want to know how many bytes have been allocated for getData function, how can I do that? @TedLyngmo – programmingEnthusiast Mar 08 '21 at 16:07
  • 1
    Why do you need to know? What problem does that knowledge solve? If it's plain curiosity, then please [edit] your question to say so, otherwise please ask about the actual and underlying problem you have instead. – Some programmer dude Mar 08 '21 at 16:15
  • 1
    @programmingEnthusiast Functions are not objects and do not have a size, as far as the language is concerned. You will need to be more precise about what you mean by "bytes allocated for `getData` function" because this is not a concept that is recognized by C++ and there are several plausible interpretations. If you share why you need this information, it may help us understand what exactly you are asking bout. – François Andrieux Mar 08 '21 at 16:17
  • ... and in your example, the function may be completely optimized away and take `0` bytes. – Ted Lyngmo Mar 08 '21 at 16:24
  • @FrançoisAndrieux The underlying motive is to have a better understanding memory allocation for objects in a class. – programmingEnthusiast Mar 10 '21 at 02:45

0 Answers0