David Turner
David Turner

Reputation: 57

How does c++ allocate class methods

Basically, I have not been able to find much information about this on the internet, but I understand that the basic class instantiation is: -> operator new() -> allocates memory from somewhere -> constructor -> assigns values to "data types"

Now, what I want to know is, how does C++ allocate methods/functions of the class rather than its members. According to my web research, this cannot happen in new() because it is only allocating raw memory, and as far as I have gotten, I have not quite been able to figure out how this could be done in the constructor with functions (rather than function pointers). Also, I assume that because of the existence of the keyword static, without this keyword, it is allocated as part of the parent class. How and where does this happen?

Also, if the functions are included in the memory of the class, does the function sizeof() give the size of just the class and its members, or does it also include the related functions?

Upvotes: 3

Views: 267

Answers (1)

Aman Deep Gautam
Aman Deep Gautam

Reputation: 8737

While compiling the code compiler takes stores the addresses of the starting point of the functions in the raw code. This address can be relative the starting location of the program or an absolute memory address.

The point is when the function is called the(assuming that scope issues are taken care of) in the code, while compiling the compiler just insert a jump statement to the address where the code of the function is present. For returning to the same location, there is some other operations taking place.

So when you say space is allocated, it just the space occupied by bytecode of the function plus the entry in a table inn compiler which says this function is present at this address

This is pretty much the case with every programming language(which compiles) not only C++.

As for your other part: sizeof(type) returns size in bytes of the object representation of type which is basically an aggregation of size of its members(if we leave out the padding which is done by compiler for optimization).

Upvotes: 3

Related Questions