Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 573
Moeb Avatar asked Jan 19 '10 06:01

Moeb


People also ask

Does new allocate memory?

new operator. The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, a new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

Is memory allocated for class?

The memory is only allocated to the variables of the class when the object is created. The memory is not allocated to the variables when the class is declared.

Which memory is allocated for a function when function is?

Explanation: Memory is allocated to variable dbl(or var) at compile time in the stack memory. Not correct, it is allocated in run-time, just as all other stack variables. That's the whole point of using a stack. It is allocated when your function is called, in run-time.

How is memory allocated to a class and its objects?

When you declare a variable or an instance of a structure or class. The memory for that object is allocated by the operating system. The name you declare for the object can then be used to access that block of memory.


1 Answers

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.

like image 116
GManNickG Avatar answered Sep 21 '22 20:09

GManNickG