Advertisement
weberc2

C OOP: Inheritance & function overloading

Jul 3rd, 2014
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2.  
  3. ///////////////////////////////////////
  4. // Base
  5.  
  6. typedef struct _base
  7. {
  8.    char*(*GetName)(struct _base*);
  9.    char* name;
  10. } Base;
  11.  
  12. char* base_get_name(Base* base)
  13. {
  14.    return base->name;
  15. }
  16.  
  17. void base_init(Base* base, char* name)
  18. {
  19.    base->name = name;
  20.    base->GetName = &base_get_name;
  21. }
  22.  
  23. ///////////////////////////////////////
  24. // Derived
  25.  
  26. typedef struct
  27. {
  28.    // by making the parent struct the first data member
  29.    // of the derived struct, a `Derived*` can be cast into
  30.    // a `Base*` for pseudo-polymorphism; however, you lose
  31.    // out on static type checking because of this cast, so
  32.    // an `int*` passed in will cause a crash at runtime
  33.    Base Base;
  34. } Derived;
  35.  
  36. char* derived_get_name(Base* derived)
  37. {
  38.    return "derived";
  39. }
  40.  
  41. void derived_init(Derived* derived)
  42. {
  43.    derived->Base.name = "";
  44.    derived->Base.GetName = &derived_get_name;
  45. }
  46.  
  47. //////////////////////////////////////
  48. // Functions
  49.  
  50. void PrintName(Base* base)
  51. {
  52.    printf("%s\n", base->GetName(base));
  53. }
  54.  
  55. int main()
  56. {
  57.    Base b;
  58.    base_init(&b, "base");
  59.    PrintName(&b);
  60.  
  61.    Derived d;
  62.    derived_init(&d);
  63.    PrintName((Base*)(&d));
  64.  
  65.  
  66.    // This would compile (because the cast breaks static
  67.    // type checking), but crash:
  68.    // int i = 40;
  69.    // PrintName((Base*)(&i);
  70.  
  71.    return 0;  
  72. }
  73.  
  74. // output:
  75. // base
  76. // derived
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement