Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- ///////////////////////////////////////
- // Base
- typedef struct _base
- {
- char*(*GetName)(struct _base*);
- char* name;
- } Base;
- char* base_get_name(Base* base)
- {
- return base->name;
- }
- void base_init(Base* base, char* name)
- {
- base->name = name;
- base->GetName = &base_get_name;
- }
- ///////////////////////////////////////
- // Derived
- typedef struct
- {
- // by making the parent struct the first data member
- // of the derived struct, a `Derived*` can be cast into
- // a `Base*` for pseudo-polymorphism; however, you lose
- // out on static type checking because of this cast, so
- // an `int*` passed in will cause a crash at runtime
- Base Base;
- } Derived;
- char* derived_get_name(Base* derived)
- {
- return "derived";
- }
- void derived_init(Derived* derived)
- {
- derived->Base.name = "";
- derived->Base.GetName = &derived_get_name;
- }
- //////////////////////////////////////
- // Functions
- void PrintName(Base* base)
- {
- printf("%s\n", base->GetName(base));
- }
- int main()
- {
- Base b;
- base_init(&b, "base");
- PrintName(&b);
- Derived d;
- derived_init(&d);
- PrintName((Base*)(&d));
- // This would compile (because the cast breaks static
- // type checking), but crash:
- // int i = 40;
- // PrintName((Base*)(&i);
- return 0;
- }
- // output:
- // base
- // derived
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement