I really do like the relative simplicity of plain c and recently have become curious about doing some basic object oriented things in plain c such as inheritance. I have read about how type punning (casting a pointer to different types) is not strictly allowed by the c standard and may cause serious bugs with certain compilers or compiler options, and that using unions tricks can be similarly problematic. The obvious solution to me is the following, for example:
#include <stdio.h>
#include <stdlib.h>
struct person;
struct cowboy;
typedef struct person Person;
typedef struct cowboy Cowboy;
struct person {char* greeting;};
struct cowboy {Person super; char* greeting;};
void Person_init(Person* aPerson)
{
aPerson->greeting = "Hello";
}
void Cowboy_init(Cowboy* aCowboy)
{
Person_init(&(aCowboy->super));
aCowboy->greeting = "Howdy";
}
void main()
{
Cowboy myCowboy;
Cowboy_init(&myCowboy);
printf("myCowboys greeting: %s\n", myCowboy.greeting);
printf("myCowboys superclass greeting: %s\n", myCowboy.super.greeting);
printf("Address of myCowboy: %d\n", &myCowboy);
printf("Address of myCowboys superclass: %d\n", &(myCowboy.super));
return 0;
}
Output:
myCowboy's greeting: Howdy
myCowboy's superclass greeting: Hello
Address of myCowboy: 2686744
Address of myCowboy's superclass: 2686744
What seems strange to me though is that while this doesn't seem to violate the c standard, just like type punning, &(aCowboy->super) does return the same address as &myCowboy, but as a different pointer type. It therefor is hard for me to believe that type punning is any less correct than my solution OR that my solution is any more correct than type punning (and how could my solution not be correct?)
I'd appreciate your thoughts on this matter,
Thanks,
Tobey












