Pointers and Classes :: Trying to grasp further

Hello Everyone,

I understand the basics of pointers and classes, but there is still a lot I don't comprehend. I understand that passing a parameter by reference is far more efficient than passing it by value... but this leads me to several questions:

1). Why ever pass a parameter by value? Given pointers you can either leave original data stand, or access it directly for change... if this is all faster and more efficient, what's the use of byval anymore?

2). I've played with the following code, and clearly when I compile there are huge differences between them, but I don't understand the reasoning why:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

void add(int* x, int* y)
{
    *x = *x + *y;   //sub question... if you omit the dereferencing operator, then you are trying to 'add' the memory locations right?
}

int main(void)
{
    int x = 0;
    int y = 5;

    add(&x, &y);

    std::cout << x << std::endl;
    return 0;
}


and...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

void add(int& x, int& y)
{
    *x = *x + *y;  
}

int main(void)
{
    int* x = 0;
    int* y = 5;

    add(x, y);

    std::cout << x << std::endl;
    return 0;
}


Why is the second so badly formed?

Forgive my questions, they may be pretty beginner and confusing, but these points will really help me make it to the next step in fully understanding these concepts.

Thanks
Az
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void add(int& x, int& y)
{
    *x = *x + *y;  //WRONG references are automatically derefenced by the compiler so don't need *
//as a matter of fact the compiler will flag this as an error

}
 
int main(void)
{
   //The next two lines are wrong -- x and y are deing declared as pointers
//not only that you cannot assign pointer values in this manner
   int* x = 0;   
   int* y = 5;     
     

add(x, y);

    std::cout << x << std::endl;
    return 0;
}



Should be like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void add(int& x, int& y)
{
    x = x + y;  
}

int main(void)
{
    int x = 0;
    int y = 5;

    add(x, y);

    std::cout << x << std::endl;
    return 0;
}
As for your question no 1.
1) Because references are typically implemented by C++ using pointers, and dereferencing a pointer is slower than accessing it directly, accessing values passed by reference is slower than accessing values passed by value.

2) Security. You don't always want your value changed. So it's safer to pass it by value that way you don't have to worry about it being changed. This is especially importing in multi-threaded environments when you need thread-safe code.
Topic archived. No new replies allowed.