views:

144

answers:

2
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;
};
+1  A: 

No. Functions exist in the text page and so no space is allocated for them.

Ignacio Vazquez-Abrams
so, if my function is a virtual function (my class is abstract), will `new()` have any problems allocating space on the heap?
Amoeba
All a virtual function means is that the function is added to the vtable located in static memory. There is only one copy of a vtable per class that uses virtual functions.
Ignacio Vazquez-Abrams
@Ignacio I am looking for an answer to: http://stackoverflow.com/questions/2091426/why-cant-we-create-objects-for-an-abstract-class-in-c I think the problem is something related to memory allocation, but I cant figure it out.
Amoeba
@cambr: Instead of asking a bunch of question *you* think will help answer it, just give us some code to work with and your real problem.
GMan
@GMan I dint come across this while writing some code. I just want to know the concrete reason as to why we cannot create an object for an abstract class? Is the problem concerned with memory allocation, or is it concerned with something else? and what exactly is the problem? Thats my whole point here.
Amoeba
@cambr - the issue about not being able to instantiate abstract classes has nothing to do with memory allocation.
R Samuel Klatchko
The word "abstract" refers to the impossibility of having any objects of the class, only objects of subclasses. It has nothing to do with memory and refers to implementation of interfaces. Think of it as definition vs declaration. An abstract base class may declare some methods but not define them.
Potatoswatter
@R Samuel Klatchko: thanks for the clarification.
Amoeba
+3  A: 

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.

GMan