CSC/ECE 517 Fall 2010/ch2 5c gn

From Expertiza_Wiki
Jump to navigation Jump to search

Dynamic Dispath

Introduction

Why we need Dynamic Dispatch

How Dynamic Dispatch works

Dynamic Dispatch working in Detail

class Cat
{
    public:
        void talk() 
        {
             cout << "Meow!!";
        }
}; 

class Dog
{
    public:
        void talk() 
        {
             cout << "Bark!!";
        }
};


struct Cat
{
    int __id__; // 0
    char name[10];
};

struct Dog
{
    int __id__; // 1
    char name[10];
};

void cat_talk()
{
    printf("meow!");    
}

void dog_talk()
{
    printf("Bark!!");
}

void talk(void *object)
{
    int id = *(int *)object;
    vtable[id](); 
}

void (*vtable[2]);
vtable[0] = cat_talk;
vtable[1] = dog_talk;

Cat *c = new Cat(); 

Cat *c = malloc(sizeof(cat));
c->__id__ = 0;

Performance Evaluation

Does Dynamic Dispatching hurts in today's power packed Computers?

Conclusion

Further Reading

References