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;
};
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With