Whats the use for pointers?

I just recently began learning code, and I'm in the portion of my book where it explains pointers. I understand them completely, but on all of these forums, everyone says pointers are heart and soul of C++. Out of all the tutorials and other things, there is not one time that they use a pointer where they can just as esily assign the variables directly. So, what is the use of pointers? If anyone can post a program or some tutorial that would not be able to function without pointers would be greatly appreciated.
Linked lists (including probably std::list) wouldn't work, polymorphism as it is also wouldn't work, dynamic allocation as it is now wouldn't work...

I wouldn't say pointers are the heart and soul of C++, but they're definitely important to learn.

-Albatross
They allow you to use polymorphism - http://www.cplusplus.com/doc/tutorial/polymorphism/

They let you modify data inside functions:
1
2
3
void modify(int* data) {
    *data = 20;
}


There are some other things, but mainly those 2 IMO.
Well, I wouldn't go that far. They are much more important in C than C++, I think. But here is an (admittedly contrived) example for you:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// changes two variables at once
void add2(int* var1, int* var2) {
    if(var1) *var1 += 2;
    if(var2) *var2 += 2;
}

int main() {
    // arbitrary numbers
    int number1 = 0;
    int number2 = 20;

    std::cout<<"number1 = "<<number1<<std::endl;
    std::cout<<"number2 = "<<number2<<std::endl;

    add2(&number1, &number2);

    std::cout<<"number1 = "<<number1<<std::endl;
    std::cout<<"number2 = "<<number2<<std::endl;

    add2(&number1, &number2);

    std::cout<<"number1 = "<<number1<<std::endl;
    std::cout<<"number2 = "<<number2<<std::endl;

    // and so on...

    return 0;
}

Normally, I would use references in this case but this illustrates one use of pointers. Another (more useful, IMO) case is polymorphism.

Edit: Tch, ninja'd on both counts.
Last edited on
Topic archived. No new replies allowed.