summaryrefslogtreecommitdiffstats
path: root/polymorphism.cpp
diff options
context:
space:
mode:
authorNao Pross <naopross@thearcway.org>2018-12-08 12:58:04 +0100
committerNao Pross <naopross@thearcway.org>2018-12-08 12:58:04 +0100
commit05f2df34290af477b0fee49b75e5f56e1d6c83f9 (patch)
tree66a7214321c874be02d1a4a9b4fd3f489dc09ad8 /polymorphism.cpp
downloadcplusplus-05f2df34290af477b0fee49b75e5f56e1d6c83f9.tar.gz
cplusplus-05f2df34290af477b0fee49b75e5f56e1d6c83f9.zip
Initial commit with kinda crappy unnumbered examples
Diffstat (limited to 'polymorphism.cpp')
-rw-r--r--polymorphism.cpp46
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;
+}