Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...