diff options
Diffstat (limited to '')
-rw-r--r-- | polymorphism.cpp | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/polymorphism.cpp b/polymorphism.cpp new file mode 100644 index 0000000..89f5005 --- /dev/null +++ b/polymorphism.cpp @@ -0,0 +1,46 @@ +#include <iostream> + +// here we have a bunch of structures to represent +// 3 dimensional math vectors, one with integer values +// and another with double precision floating point values +struct vec3i { + int x; + int y; + int z; +}; + +struct vec3d { + double x; + double y; + double z; +}; + +// and we define the dot product operation +int dot(vec3i v, vec3i w) { + return v.x * w.x + v.y * w.y + v.z * w.z; +} + +// notice that this function is also called dot() like the one above +// the difference is in the return value and the arguments +// this functions is said to *overload* the one before +double dot(vec3d v, vec3d w) { + return v.x * w.x + v.y * w.y + v.z * w.z; +} + + +int main(int argc, char *argv[]) { + + vec3i a = { 1, 2, 3 }; + vec3i b = { 1, 2, 3 }; + // lets use our data and functions + std::cout << dot(a, b) << std::endl; + + vec3d c = { .5, .2, 11.2 }; + vec3d d = { .2, .2, 12.3 }; + + // notice how the compiler recognizes the type of the argument + // and calls the correct dot() function + std::cout << dot(c, d) << std::endl; + + return 0; +} |