Created
September 10, 2021 14:48
-
-
Save kolosovpetro/0f5f1cca1023dfbf767feeb178d353f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <string.h> | |
| #include <stdlib.h> | |
| struct Base_; | |
| typedef struct Base_VTable_ | |
| { | |
| char* (*ToString)(struct Base_*); | |
| } Base_VTable; | |
| Base_VTable Base_VTable_Obj; | |
| typedef struct Base_ | |
| { | |
| Base_VTable* vtable; | |
| } Base; | |
| void Base_Init(Base* this) | |
| { | |
| this->vtable = &Base_VTable_Obj; | |
| } | |
| typedef struct Derived_ | |
| { | |
| Base base; | |
| int a; | |
| } Derived; | |
| char* Derived_ToString(Derived* this) | |
| { | |
| char buffer[80]; | |
| sprintf(buffer, "%d", this->a); | |
| return strdup(buffer); | |
| }; | |
| void Derived_Init(Derived* this) | |
| { | |
| Base_Init((Base*)this); | |
| this->a = 42; | |
| ((Base*)this)->vtable->ToString = Derived_ToString; | |
| } | |
| int main() | |
| { | |
| Derived d; | |
| Derived_Init(&d); | |
| char* str = ((Base*)&d)->vtable->ToString(&d); | |
| puts(str); | |
| free(str); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment