how c++ implements the polymorphism internally?

后端 未结 4 1375
耶瑟儿~
耶瑟儿~ 2020-12-31 20:02

Respected Sir!

i should tell you that what i know and what i don\'t know about the asked question so that you can address the weak area of my understanding.

4条回答
  •  梦谈多话
    2020-12-31 20:47

    The Standard says nothing about how to implements the polymorphism. One class one vtbl and one object one vptr is the most popular way. I hope the following pseudocode would be helpful.

    typedef struct {
        void (*show)(void* self);
        // more
    
    } person_vtbl;
    
    typedef struct {
          person_vtbl* vtbl;
          char         name[20];
    } person;
    
    void person_show(void* self) {
          cout<<"inside ... "<(self)->name;
    }
    // more
    
    static person_vtbl person_vtbl_ = { &person_show }; // vtbl for person class
    
    void person_ctor(void* self, char const* name) {
          person* p = static_cast(self);
          strcpy(p->name, name);
          p->vtbl   = &person_vtbl  // vptr of person object
    }
    
    typedef struct {
        person base;
        int    scale;
    } teacher;
    
    void teacher_show(void* self) {
          cout<<"inside the tearch ... "<(self)->scale;
    }
    static person_vtbl teacher_vtbl_ = { &teacher_show };
    
    void teacher_ctor(void* self, char const* name, int s) {
          teacher* t = static_cast(self);
          person_ctor(&t->base, name);     // construct base part
          t->scale   = s;                  // construct teacher part
          t->vtbl    = &teacher_vtbl_;     // vptr of teacher object
    }
    
    // construct teacher :
    // person* ptr = new teacher("Zia", 16);
    
    teacher* tmp = static_cast( malloc( sizeof *tmp );
    teacher_ctor(tmp, "Zia", 16);  // vptr of tmp points to teacher_vtbl_
    person* ptr = &tmp->base;
    
    // call virtual function though pointer
    // ptr->show()
    
    ptr->vptr->show(ptr); // call teacher_show(ptr);
    

提交回复
热议问题