dynamiclly allocate memory for class

I'm clear about dynamically allocating memory for struct in C++.

struct Node
{
    int item;
    struct Node *next;
};

int main()
{
    struct Node *head = new struct Node;
    return 0;
}

Here is a picture.

There are 8 byte memory allocated in heap, head is a pointer to it.

But when I come across dynamiclly allocate memory for class,a few questions confused me for a longtime. There is an example:

class Example
{
private:
    int a;
    double b;
public:
    virtual void fun();
    void fun2();
};

int main()
{
    Example *e = new Example;
}

void Example::fun()
{
}

My questions is:

1.I know the system allocate memory for int and double in heap,do the system also allocate memory for fun() and fun2() in heap ? if not, where are fun() and fun2() stored in application memory ?

2.How many bytes allocated in heap?

3.How do the pointer e dereference the function fun() or fun2()?

4.What's the difference between dereference a normal function and dereference a virtual function?


First of all, a class and a struct are in C++ equivalent, the only difference is that the default access modifier is public for a struct and private for a class. And the datatype for a struct Node is just Node , so Node *head = new Node; is enough, no need to repeat the struct everywhere.

1.I know the system allocate memory for int and double in heap,do the system also allocate memory for fun() and fun2() in heap ? if not, where are fun() and fun2() stored in application memory ?

The methods reside in the code-block, together with all other functions. There is only one copy of that methods source-code, not one for each instance.

2.How many bytes allocated in heap?

This depends on padding and alignment. sizeof(Example) tells you, how many bytes the class needs.

3.How do the pointer e dereference the function fun() or fun2()?

This depends on if the method is a virtual method or not. If its not it is just compiled as if it were a regular function with the exception that the pointer to this is also passed (in a register if I'm not wrong).

For the virtual functions and #4 see here

链接地址: http://www.djcxy.com/p/14078.html

上一篇: 类成员内存分配

下一篇: 为班级dynamiclly分配内存