Hey!
Good job on this article :)
There is a point I would like to discuss:
So, why bother with any of this when you can just directly access/modify the variable that's being pointed to? By using pointers, you can create dynamic variables
So, why bother with any of this when you can just directly access/modify the variable that's being pointed to?
By using pointers, you can create dynamic variables
The main reason is because variables are passed by copy to functions in C++.
#include <iostream> using std::cout; void increase(int value) { value += 2; } int main() { int value = 2; cout << value << '\n'; increase(value); cout << value << '\n'; }
This code prints "2 2", not "2 4". This is why we need pointers. In fact, we need addresses. References work perfectly in such a situation:
void increase(int& value) { value += 2; }
By the way, with modern C++ (== C++11 and above), you should avoid calling new and delete by yourself and prefer using smart pointers:
#include <iostream> #include <memory> using std::cout; struct Foo { Foo() { cout << "create" << '\n'; }; ~Foo() { cout << "delete" << '\n'; }; }; int main() { auto pointer = std::make_unique<Foo>(); }
Output:
create delete
There are the best way to avoid memory leaks :)
Thanks for the info, Pierre! :)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hey!
Good job on this article :)
There is a point I would like to discuss:
The main reason is because variables are passed by copy to functions in C++.
This code prints "2 2", not "2 4". This is why we need pointers. In fact, we need addresses. References work perfectly in such a situation:
By the way, with modern C++ (== C++11 and above), you should avoid calling new and delete by yourself and prefer using smart pointers:
Output:
There are the best way to avoid memory leaks :)
Thanks for the info, Pierre! :)