[Solved] Passing pointers as a parameter in C++ rather than using this pointer


First thing to get straight: a non-static member function is essentially just like any other function, but has an implicit parameter called this which is a pointer to the object that the member function was called on. That is, calling foo.bar() can be thought of as similar to calling bar(&foo), where the first parameter is called this.

Now, in your first case, if you do some_box.getVolume(), it will calculate the volume of some_box, since a pointer to some_box is passed as this.

In your second case, you have exactly the same function, but you have introduced an unused parameter box. Since you’re not using it, it’s completely pointless. It would mean that you would have to pass a pointer to a box every time you called getVolume, yet that pointer wouldn’t be used at all. That is, you’d have to call either some_box.getVolume(&some_box) or some_box.getVolume(&another_box).

Now you could change every this inside the second function to box and then you would be working out the volume of the box that was passed via the pointer parameter. That is, some_box.getVolume(&another_box) would give you the volume of another_box. But now the implicit this parameter is unused and pointless! Now you might as well make it either a static member function or just a non-member function.

If you were to do this, you’re basically just mimicking the idea of member functions – instead of an implicit this parameter, you have an explicit box parameter. What’s the point? The language feature of member functions is a neater way of doing this.

1

solved Passing pointers as a parameter in C++ rather than using this pointer