Skip to content

Instantly share code, notes, and snippets.

@grahamwren
Last active April 14, 2020 18:00
Show Gist options
  • Save grahamwren/f82e43c26bc6d8c0f6cd0254a7701c26 to your computer and use it in GitHub Desktop.
Save grahamwren/f82e43c26bc6d8c0f6cd0254a7701c26 to your computer and use it in GitHub Desktop.
Cpp Const Pointer Demo
run: test_const_pointers.o
./test_const_pointers.o
test_const_pointers.o: test_const_pointers.cpp
g++ test_const_pointers.cpp -o test_const_pointers.o -std=c++11
clean:
rm *.o
#include <assert.h>
class Number {
public:
int _number;
Number(int num) : _number(num) {}
void add(Number *n) { _number = _number + n->_number; }
bool equals(Number *n) { return n->_number == _number; }
};
int const_pointer_ex(Number *const n) {
Number new_n(5);
*n = new_n;
// n++; // produces compile error
return 0;
}
int pointer_to_const_value_ex_1(Number const *n) {
Number new_n(5);
// *n = *new_n; // REVIEW: produces compile error
n++;
return 0;
}
int pointer_to_const_value_ex_2(const Number *n) {
Number new_n(5);
// n->add(new_n); // REVIEW: produces compile error
n++;
return 0;
}
int const_pointer_to_const_value_ex(const Number *const n) {
Number new_n(5);
// n->add(new_n); // REVIEW: produces compile error
// n++; // REVIEW: produces compile error
return 0;
}
int const_reference_ex(const Number &n) {
const Number new_n(5);
// n.add(new_n); // REVIEW: compile error
// n = new_n; // REVIEW: compile error
return 0;
}
int main() {
Number n20_i(20);
const_pointer_ex(&n20_i);
Number n5_e(5);
assert(n20_i.equals(&n5_e));
Number n40_i(40);
pointer_to_const_value_ex_1(&n40_i);
Number n40_e(40);
assert(n40_i.equals(&n40_e));
Number n30_i(30);
pointer_to_const_value_ex_2(&n30_i);
Number n30_e(30);
assert(n30_i.equals(&n30_e));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment