Last active
December 22, 2019 05:48
-
-
Save George-lewis/f5a64164b50f227ae3c023943eb54ed0 to your computer and use it in GitHub Desktop.
Virtual in 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
/////////////////////////////////////////////////////////////////////////////////////////////// | |
// Demonstrates a sort of pseudo-polymorphism in C using similar methods to the C++ compiler // | |
/////////////////////////////////////////////////////////////////////////////////////////////// | |
typedef struct vtable { // Virtual table for holding methods | |
int (*process)(int); // Pointer to a function that returns an int and takes in an int | |
} vtable; | |
typedef struct NumberProcessor { // "class" that processes an integer | |
const vtable* vtable; // Method table | |
} NumberProcessor; | |
int square(int a) { return a*a; } | |
int third(int a) { return a*a*a; } | |
const vtable vsquare = { square }; | |
const vtable vthird = { third }; | |
int proc(NumberProcessor* nproc, int n) { // "polymorphic" function | |
return nproc->vtable->process(n); // Get function ptr from vtable | |
} | |
int main() { | |
NumberProcessor square_ptr = { &vsquare }; // Squares a number | |
NumberProcessor third_ptr = { &vthird }; // Computes n*n*n | |
printf("%i\n", proc(&square_ptr, 5)); // Prints 25 (5*5) | |
printf("%i\n", proc(&third_ptr, 3)); // Prints 27 (3*3*3) | |
} |
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
////////////////////////////////////////////////////////// | |
// Demonstrates the usage of the virtual keyword in C++ // | |
////////////////////////////////////////////////////////// | |
#include <iostream> | |
// Structs work the same as classes in C++ except their members are public by default | |
struct base { | |
virtual int get() { return 5; } | |
}; | |
struct derived : public base { | |
int get() { return 7; } | |
}; | |
int get(base* b) { // Polymorphic function | |
return b->get(); | |
} | |
int main() { | |
base* b1 = new Base; | |
std::cout << b1->get() << std::endl; // Prints 5 | |
std::cout << get(b1) << std::endl; // Prints 5 | |
base* b2 = new derived; | |
std::cout << b2->get() << std::endl; // Prints 7 | |
std::cout << get(b2) << std::endl; // Prints 7 | |
derived* d = new derived; | |
std::cout << d->get() << std::endl; // Prints 7 | |
// Cleanup | |
delete b1; | |
delete b2; | |
delete d; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment