Hello,
I am trying to make a struct type and make another struct built on top of the other struct and I got it working, but I'm not sure what the tutorial means when it says I need to do pointer casting. I know how, but not sure why I have to do this? I seem to have it going without the casting so I'm not sure why they mentioned it. Can anyone help me understand why?
my code:
#include <stdio.h>
#include <string.h>
typedef struct {
float wage;
char name[15];
} Employee;
typedef struct{
Employee super;
char title[15];
} Manager;
int main(int argc, const char * argv[])
{
Manager manager1;
strcpy(manager1.super.name, "Steve");
strcpy(manager1.title, "Manager On Duty");
Manager manager2;
strcpy(manager2.super.name, "Jack");
strcpy(manager2.title, "CEO");
printf("Title:\t\t\t\tEmployee Name:\n%s\t\t%s\n", manager1.title, manager1.super.name);
printf("%s\t\t\t\t\t%s\n", manager2.title, manager2.super.name);
return 0;
}
tutorial code: (not same example)
typedef struct
{
// base members
} Base;
typedef struct
{
Base base;
// derived members
} Derived;
then they say "As Derived starts with a copy of Base, you can do this:"
Base *b = (Base *b)d;
"Where d is an instance of Derived. So they are kind of polymorphic. But having virtual methods is another challenge - to do that, you'd need to have the equivalent of a vtable pointer in Base, containing function pointers to functions that accept Base as their first argument (which you could name this)"