Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

c++ - Where are functions of an object stored in memory?

Suppose we have a class:

class Foo
{
private:
    int a;
public:
    void func()
    {
       a = 0;
       printf("In Func
");
    }
}

int main()
{
    Foo *foo = new Foo();
    foo->func();
    return 0;
}

When the object of the class Foo is created and initialized, I understand that integer a will take up 4 bytes of memory. How is the function stored? What happens in memory / stack /registers / with the program counter when calling foo->func()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The short answer: It will be stored in the text or code section of the binary only once irrespective of the number of instances of the class created.

The functions are not stored separately anywhere for each instance of a class. They are treated the same way as any other non-member function would be. The only difference is that the compiler actually adds an extra parameter to the function,which is a pointer of the class type. For example the compiler will generate the function prototype like this:

void func(Foo* this);

(Note that this may not be the final signature. The final signature can be much more cryptic depending on various factors including the compiler)

Any reference to a member variable will be replaced by

this-><member> //for your ex. a=0 translates to this->a = 0;

So the line foo->func(); roughly translates to:

  1. Push the value of Foo* on to the stack. #Compiler dependent
  2. call func which will cause the instruction pointer to jump to the offset of func in the executable #architecture dependent Read this and this
  3. Func will pop the value from stack. Any further reference to a member variable would be preceded by dereferencing of this value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...