summaryrefslogtreecommitdiffstats
path: root/references.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'references.cpp')
-rw-r--r--references.cpp44
1 files changed, 44 insertions, 0 deletions
diff --git a/references.cpp b/references.cpp
new file mode 100644
index 0000000..be40a50
--- /dev/null
+++ b/references.cpp
@@ -0,0 +1,44 @@
+#include <iostream>
+
+// a basic new feature of C++ are references, they are like
+// pointers, but they *can't* be null, which btw in c++ is `nullptr'
+
+
+// here is a typical C example to use pointers
+void inc_ptr_val(int *v) {
+ // check that v is not null
+ if (v == nullptr) {
+ return;
+ }
+
+ // increment where v points
+ (*v)++;
+}
+
+// and here is a new (better) version
+void inc_ref_val(int& v) {
+ // no need to check
+ // no need to dereference
+ v++;
+}
+
+// an interesting twist is that we can now have const references
+// which is like a C "T const * const" ie read only reference
+// and is used to not copy big things on the stack
+bool is_hello(const std::string& s) {
+ // s cannot be changed, only read
+ return s == "hello";
+}
+
+
+int main(int argc, char *arg[]) {
+
+ int hello = 10;
+ std::cout << hello << std::endl;
+
+ inc_ptr_val(&hello);
+ std::cout << hello << std::endl;
+
+ inc_ref_val(hello);
+ std::cout << hello << std::endl;
+}