开发者

Does new() allocate memory for the functions of a class also?

开发者 https://www.devze.com 2022-12-16 16:50 出处:网络
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 funct
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号