Last active
March 15, 2016 14:27
-
-
Save alexshpilkin/e5c7bc9baa32d43389ca to your computer and use it in GitHub Desktop.
Polymorphism in C++ and plain C
This file contains 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 <stdlib.h> | |
struct A { | |
struct Atable *vptr; | |
}; | |
struct Atable { | |
int (*answerp)(struct A *this); | |
}; | |
struct B { | |
struct A base; | |
double question; | |
}; | |
int A_answer(struct A *this) { | |
return 42; | |
} | |
struct Atable A_Atable = { &A_answer }; | |
int B_answer(struct B *this) { | |
return this->question; | |
} | |
struct Atable B_Atable = { (int (*)(struct A *))&B_answer }; | |
/* correct for different type of 'this' */ | |
int main(void) { | |
struct A *a; struct B *b; | |
a = malloc(sizeof(struct A)); a->vptr = &A_Atable; | |
b = malloc(sizeof(struct B)); b->base.vptr = &B_Atable; | |
b->question = 57; | |
struct A *aa = (struct A *)b; | |
printf("%d %d\n", (*a->vptr->answerp)(a), (*aa->vptr->answerp)(aa)); | |
free(a); free(b); | |
return 0; | |
} |
This file contains 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 <cstdio> | |
// Virtual destructors in A and B omitted for brevity, although technically it | |
// means undefined behaviour | |
class A { | |
public: | |
virtual int answer(void); | |
}; | |
class B : public A { | |
public: | |
virtual int answer(void); | |
int question; | |
}; | |
int A::answer(void) { | |
return 42; | |
} | |
int B::answer(void) { | |
return this->question; | |
} | |
int main(void) { | |
A *a = new A(); | |
B *b = new B(); | |
b->question = 57; | |
A *aa = b; | |
std::printf("%d %d\n", a->answer(), aa->answer()); | |
delete a; delete b; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment