user3506381
user3506381

Reputation: 1

Static Methods Vs Non-Static Methods[dulicate]5

I have a question about what happens at runtime.

Let's say I created an object. There is a reference on the stack to the space where the object 1st stored in the heap.

The DataMembers( int a=10 ....) are stored in the space of the object. If the class of the object would have virtual methods there would be a vpointer of 8 Bytes to a VirtualTable on another Address on the heap.

Let's say I have only non static Methods. So The Object only stores a pointer to a Method Table of the Type Object of my Class.

I hope I'm right with my first part :)

if im right....I'm wondering what happens when the native Constructions want to call a non static Method of my Object?! and where the non static Methods really are stored? cause there has to be a difference to the space where the static methods were stored (they are stored at the Type Object table of the calls...right!?)

My suggestion:

The Methodtable of the Type Object of my Class has the name of the called Method. This Method gets some space at the stack called the stack frame. This frame stored the parameters of the Method plus an invisible constant pointer called this. This pointer refers to the address of the object on the heap.

Upvotes: 0

Views: 42

Answers (1)

Servy
Servy

Reputation: 203802

The code for every method is stored somewhere in memory. It's not really relevant where that is.

Whenever code calls a static method, or a non-virtual instance method, the compiler knows at compile time the exact code that needs to be called. It can ensure that the code can directly reference the appropriate method's code. That's it; it's done. The call site just has a direct reference to the method.

For a non-static virtual method, the compiler doesn't know at compile time what method is actually executed. Every single reference type object, among the data representing that object, has some type information. When that virtual method is called, the object is inspected for its type information. This type information includes a v-table; a table that indicates a reference to what block of code should be run for any given method. The method that needs to be run is plugged into this table, and out pops a reference to the method that should be run.

Upvotes: 1

Related Questions