DEV Community

Discussion on: C++ Pointers

Collapse
 
pgradot profile image
Pierre Gradot • Edited

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

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';
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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>();
}
Enter fullscreen mode Exit fullscreen mode

Output:

create
delete
Enter fullscreen mode Exit fullscreen mode

There are the best way to avoid memory leaks :)

Collapse
 
robotspacefish profile image
Jess

Thanks for the info, Pierre! :)