Does new() allocate memory for the functions of a class also?
class Animal
{
public:
int a;
double d;
int f(){ return 25;}
};
Suppose for the code above, I try to initialize an object, by saying new Animal()
, does this new()
also allocate memory for the function f()
?
In other words, what is the difference in memory allocation terms if I had this class instead and did a new Animal()
? :
class 开发者_运维技巧Animal
{
public:
int a;
double d;
};
For a class with no virtual functions, the function themselves take up no data space. Functions are sections of code that can be executed to manipulate data. It is the data members that must be allocated.
When you have a virtual class, often there is an extra pointer for virtual table. Note that a vtable is an implementation specific detail. Though most compilers use them, you can't count on it always being there.
I've expanded on this answer on your other question.
No. Functions exist in the text page and so no space is allocated for them.
精彩评论