I’m trying to find out/understand exactly how you access data of an object using free functions.
So my free functions look like this (header wise anyways):
#ifndef CDSUPPORTFUN_H
#define CDSUPPORTFUN_H
void DisplayCDS(CDX *pCD1, CDX *pCD2, CDX *pCD3);
void ShowCosts(CDX &CD1, CDX &CD2, CDX &CD3);
void MemoryReturn(CDX *pCD1, CDX *pCD2,CDX *pCD3);
#endif
Then I have the implementation for what each does. My question is, exactly what do I input into my Main.cpp to access these functions? What information must I pass in the Main.cpp when I call them?
For example, when I use:
DisplayCDS(pCD1, pCD2, pCD3);
My data is displayed as intended. However is this still passing with a pointer? And how should it look if I am passing my reference?
—
EDIT: Since ShowCosts is passing by reference would the appropriate syntax to retrieve it be:
CD1.ReturnCosts();
To clear things up, there are two ways to pass by reference. You can pass pointers, which point to an instance of an object. Or you pass the actual object to the function, and have the function create references to those objects. To pass by reference with pointers (the way you have it):
Define your function as:
and in your Main, call it as:
Alternatively, if you don’t like pointers, you can define your function to take references and pass an actual object to it rather than a pointer. To do this:
Define your function as:
and in your Main, call it as:
These two syntaxes accomplish the same thing. You have passed a reference to your function and not copied the object. Note that there will be a difference in how you use pCD1 or CD1 in your function now. If using pointers, you’ll have to use pCD1 as:
or
If you used the second syntax, you’ll be able to use the object in your function as normal:
Just to further demonstrate how pointers work, you could also use this method, which is a combination of the previous two, and is unnecessarily confusing.
Define your function as
And in Main:
All of these examples should work…I prefer using the CDX& syntax to avoid the use of *’s all over the place. And ->’s.
EDIT: As pointed out in the comments, passing a pointer is not technically “passing by reference”. It is passing an object (a pointer) that points to your object in memory.