How to pass parameters for output in C++ [duplicate] - c++

This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 9 years ago.
Some of methods that I see in C++ code are of this structure:
void Class::method1(int &a);
and are called like this:
int a;
class->method1(a);
But sometimes I see structures like:
void Class2::method2(int* a);
And these methods are called like this:
int a;
class2->method2(&a);
I understand that in the first case the method accepts an address of a variable, and in the second - pointer to a variable, right?
Could someone explain to me what is the difference between these two approaches, and when to use which?
Also, in the first example, it seems that a method can be taking "int& a" or "int a", and in both cases we would call it the same way: int a; class->method1(a); ? This seems confusing.
Thanks.

void Class::method1(int &a);
This is passing by reference.
void Class2::method2(int* a);
This is passing the pointer. In class2->method2(&a);, & is the address of operater.

First one is called using a reference to a variable, second one - using a pointer. There are some difference between the two concepts. I encourage you to google this, but the most important ones I can think of right now are that a reference can not be constructed without pointing to an existing object and that a pointer can be NULL.

void Class::method1(int &a) means you are passing a by reference and the caller can expect a to be modified.
void Class2::method2(int* a) means you are passing a by pointer and the caller can expect the thing to which a points to be modified.
Personally I don't like pass by reference since the caller doesn't quickly know if a will be modified as the calling syntax for pass by reference and pass by value are identical. Passing by constant reference void Class::method1(const int &a) is better still since then a cannot be modified and you can gain an efficiency in not taking value copies if a is a large object.
However many folk differ in their opinion and say that you should pass by pointer if the function allows the pointer to be null; i.e. can your function do something useful without a inputted?

In the first case, the method accept a reference to the variable.
It means that if a is modified inside the method1, it will be modified after the function returns.
In the second case, it accepts a pointer to the variable. A pointer is the memory adress of the variable. It's what the & retrieves : The address (aka a pointer to a).
Both type have essentially the same purpose : Being able to modify a variable of a different scope.
See that example :
void fooPointer (int* pointer) {
*pointer += 1;
}
void fooReference (int& reference) {
reference += 1;
}
int main () {
int a = 0;
std::cout << a; // Ouputs 0
fooPointer (&a);
std::cout << a; // Outputs 1
fooReference (a);
std::cout << a; // Outputs 2
}
As you can see, both allow you to do the same here. But using references is usually easier and more readable, because everything is done implicitly, so you don't have to reference (*) or dereference (&) your variables.

Related

`this` Pointer for Temporary [duplicate]

This question already has answers here:
Why is taking the address of a temporary illegal?
(7 answers)
Closed 8 months ago.
Consider the following C++ code:
class Func {
public:
void operator()() const { std::cout << this; }
};
int main() {
Func()(); // OK
std::cout << &Func(); // Can't take address of a temporary
}
In the body of operator(), it is completely valid to treat this as any other pointer. However, we're told time and again that we can't take the address of a temporary, yet that seems to me to be exactly what's happening. The first line of main is perfectly fine, yet semantically, the line below it is identical. If I were to try to implement this in C to understand what's going on, I might dream up the following (C code):
typedef struct {} Func;
Func construct_Func() {
Func result;
return result;
}
void Func_operator_invoke(const Func* const this) {
printf("%p", this);
}
int main() {
Func_operator_invoke(&construct_Func()); // Can't take address of a temporary
}
Here, though, we run into a snag: we can't call our "simulated member function" on a temporary... which then begs the question -- why can we call member functions on temporaries in C++? If we can't take the address of a temporary, why can we pass the address of a temporary into a (member) function? Why is that any more valid than passing the address of a temporary into a free function?
Now, I fully expect that the answer to my question is "that's just how it is". That said, let me pose another question to preempt that answer: what does the standard say about calling member functions on temporary objects, and what is a reasonable way for a compiler to implement this? Could it simply push the temporary onto the stack, then pass the pointer to that memory to the function? If so, what's the reasoning behind the C and C++ standards not allowing similar behavior when taking the address of a temporary? As in, why doesn't the C code Func_operator_invoke(&(construct_Func())) simply create an object, then pass a pointer to that object? Is there a published or well-known reason at all?
There's nothing wrong with using this inside a member function. It's a valid pointer while that function is executing. The temporary object is destroyed after at the end of the full-expression (the ;).
So in Func()();
A temporary instance of Func is created
Func::operator() is executed
std::cout operator << is executed
The temporary is destroyed
This can't be reproduced with C as C has no classes nor member functions.
With regard to taking an address of a temporary, it's clearly an error as there's no possible valid use for it. For more details refer to Why is taking the address of a temporary illegal?

Reassigning pointer argument inside function in C++ [duplicate]

This question already has answers here:
pass by reference and value with pointers [duplicate]
(5 answers)
Is passing pointer argument, pass by value in C++?
(5 answers)
Closed 10 months ago.
If I pass a pointer to a function as an argument and assign to the pointer inside the function, shouldn't that be reflected in the calling scope?
In the following code, s==nullptr gets printed. Why did assignment to s inside the function assign_string not reflected in the main function?
#include<iostream>
#include<string>
void assign_string(std::string* s)
{
s = new std::string("Reassigned");
}
int main()
{
std::string* s = nullptr;
assign_string(s);
if (s == nullptr)
{
std::cout << "s==nullptr" << std::endl;
}
else
{
std::cout << "s!=nullptr" << std::endl;
}
return 0;
}
PS: I'm new to C++ and I might be using terms like "assign" loosely.
EDIT.
Is passing pointer argument, pass by value in C++? has many useful answers.
If I pass a pointer to a function as an argument and assign to the pointer inside the function, shouldn't that be reflected in the calling scope?
No. When you pass an object by value, the parameter and the argument are separate objects. Modifying one object has no effect on the other object. This applies to all objects, including pointers.
In order to modify an object outside of the function, you need to use indirection. There are two forms of indirection: Pointers and references. So, in order to modify a pointer that is outside of the function, you need to pass a reference or a pointer to the pointer. Example:
void assign_string(std::string*& s);
PS: I'm new to C++
I recommend learning early that owning bare pointers are a bad idea and there is hardly ever a need to use them nor to use allocating new expressions. It's quite rare to need to dynamically allocate a std::string object or any other container.

C++ function parameter takes an address of a pointer as an argument. How is this used? What is it for?

Imagine a function like this:
function(Human *&human){
// Implementation
}
Can you explain what exactly a *& is? And what would it be used for? How is different than just passing a pointer or a reference? Can you give a small and explanatory sample?
Thank you.
It is like a double pointer. You're passing the pointer by reference allowing the 'function' function to modify the value of the pointer.
For example 'human' could be pointing to Jeff and function could modify it to point to Ann.
Human ann("Ann");
void function(Human *& human)
{
human = &ann;
}
int main()
{
Human jeff("Jeff");
Human* p = &jeff;
function(p); // p now points to ann
return 0;
}
void doSomething(int &*hi);
will not work. You cannot point to references. However, this:
void doSomething(int *&hi); // is valid.
It is a reference to a pointer. This is useful because you can now get this pointer passed into the function to point to other "Human" types.
If you look at this code, it points "hi" to "someVar". But, for the original pointer passed to this function, nothing will have changed, since the pointer itself is being passed by value.
void doSomething(int *hi)
{
hi = &someVar;
}
So you do this,
void doSomething(int *&hi)
{
hi = &someVar;
}
So that the original pointer passed into the function is changed too.
If you understand "pointers to pointers", then just imagine that, except when something is a reference it can be treated like a "non-pointer".
"Takes an address of a pointer" - No, it doesn't. It takes supposed to take a reference to a pointer.
However, this is a syntax error. What you probably meant is
rettype function(Human *&human)
(Yes, it's also missing a return type...)
Since you wrote this code off the top of your head, I'm going to assume you meant to do something like this:
void f(T *&) {}
This function signature allows the pointer passed to become modifiable, something that isn't allowed with the alternate syntax int *. The pointer is effectively passed by reference as others here call it.
With this syntax, you are now able to modify the actual pointer and not just that which it points to. For example:
void f(int *& ptr) {
ptr = new int;
}
int main() {
int * x;
f(ptr); // we are changing the pointer here
delete x;
}
Summary (assume types are in parameters):
T *: We are only able to change the value of the object to which the pointer points. Changing the parameter will not change the pointer passed.
T *&: We can now change the actual pointer T, and the value of the object to which it points *T.
Even though it looks just like the address-of operator, it's not - it's a reference parameter. You use a reference when you want to be able to change the value at the caller's end. In this case the pointer is probably being set or changed within the function.

when i need pass by pointer (and not by reference)

Can you give me an example when I can't pass argument by reference and I need to use pointer. I've found an example, but I'm not sure.
Suppose you have a class D derived from the base class B. You need pointer if you want do so:
void function(B* b){...}
int main{
D* d;
function(d);
}
The single time where you can not use a reference and must use a pointer is if you allow the concept of "no argument" by passing a null pointer.
However, you might want to use pointers as arguments when you are actually storing a pointer to whatever was passed. Most C++ developpers will notice that you aren't using a reference and pay special attention to what your documentation says.
If there is a coding guideline (like Google's) that says to use pointer arguments, then that's what you do.
Otherwise, only declare your own function with pointer formal argument when
a nullpointer is a valid & meaningful actual argument, or
the actual argument is most naturally pointer already, or
you're going to store that pointer somewhere.
Possibly more cases, but I think you get the drift: when you have a choice (no coding guideline saying otherwise), prefer references.
Cheers & hth.,
Another case: if the thing you're passing is the last argument before varargs:
void fn1(A &a, ...); // Uh oh
void fn2(A *a, ...); // Good
I don't know if this is required by the standard, or is just a bug in the implementation of the C++ compiler I use.
Typically, you use pointers for one of two things:
Reassignability - you can't rebind a
reference.
Null pointers - there's no such
thing as a null reference.
If your intended use case does not need either of those two properties, use a reference. Else, use a pointer.
If you want to allow the lack of an object, you need to use pointers:
// This allows DoSomething to receive pointers to NULL, which cannot
// be done with references
void DoSomething(Something *pSomething)
{
if (pSomething)
{
...
}
}
int main()
{
Something *pSomething=NULL;
DoSomething(pSomething);
}
http://www.daniweb.com/forums/thread216353.html
Singly linked lists example were pointers and pointer of pointers are used as function parameters.
the only reason is if you need to pass null. I.e you want to call the function saying 'I haven't got one of those'
I think that if you want to pass a function, you have to pass it by pointer. I don't see how you can pass the function by reference.
For example, take the following function:
#include <iostream>
#include "math.h"
void myfun (double value, size_t nofloops, double (*function)(double))
{
std::cout << value << std::endl;
for (size_t i=0;i<nofloops;++i)
{
value = function(value);
std::cout << value << std::endl;
}
std::cout << "------------------" << std::endl;
}
void main()
{
myfun(100,10,sin);
myfun(100,10,cos);
myfun(100,10,sqrt);
}
The function in this small utility executes the given function a number of times, taking the result as input in the next iteration. I can't see how you can pass the function by reference.

C++ Parameter Reference

void (int a[]) {
a[5] = 3; // this is wrong?
}
Can I do this so that the array that is passed in is modified?
Sorry for deleting, a bit new here...
I have another question which might answer my question:
If I have
void Test(int a) {
}
void Best(int &a) {
}
are these two statements equivalent?
Test(a);
Best(&a);
void Test(int a[])
{
a[5] = 3;
}
just alternate syntax for:
void Test(int* a)
{
*(a+5) = 3;
}
No array is passed, just a pointer. The original array is modified.
As for your second revision, given:
void Test(int a)
{
}
void Best(int &a)
{
}
then
Test(aa); // Passes aa by value. Changes to a in Test() do not effect aa
Best(aa); // Passes aa by reference; Changes to a DO effect aa
Best(&aa); // Is a syntax error: Passing a pointer instead of an int.
If you get the variable not by reference and not by pointer, it means that the function is essentially isolated, getting an ad-hoc copy of a. No matter what you do (without trying to hack the stack or things like that) you wouldn't have access to that value in the calling context.
If you know something about the calling context, you may be able to do things based on some anticipation of stack contents, but it's generally a bad idea.
If your method takes a[] which is essentially a*, then yes, you can alter the contents of the cell that a points to, but you won't be able to alter a (the pointer) itself to point at something else.
Nope.
Your options for altering a value from outside the function are call by reference f(int& a), call by pointer f(int* a), and using a global (shudder...) variable.
Read the answer given here about the difference of int[] and int* in a parameter list: Difference between char* and char[] . I've really put so much love into that answer! :)
Regarding your question about your Test and Best functions, James Curran provided an excellent answer.
Your original Function should work.
If you give it a name:
#include <iostream>
// Arrays always de-generate to pointers.
void plop(int a[]) // Make sure this function has a name.
{
a[5] = 3;
}
int main()
{
int test[] = { 1,1,1,1,1,1,1,1};
plop(test);
std::cout << test[5] << std::endl;
}
This is because arrays always de-generate into pointers when passed as an argument to a function. So this should always work as expected. Assuming you don't index beyond the end of the array. Inside plop there is no way to determine the size of the array passed.
The primary motivator for passing arrays by reference is to prevent stack overflows and needless copying of large objects. For example, imagine if I had a function like this:
void foo(int x[500000000000]);
The stack would probably overflow the first time you called the function if all arrays were passed by value (but of course this is an obvious exaggeration).
This will become useful when using object-oriented methods. Suppose instead of an array, you had this:
void foo(SomeClass x);
where SomeClass is a class with 500000000000 data members. If you called a method like this, the compiler would copy x bit by bit, which would be a very long process to say the least. The same concept as you use in arrays still applies, but you have to specify that this is to be used by reference manually:
void foo(SomeClass &x);
(and don't go trying to create a 500000000000 element array to begin with unless you have a 64 bit machine and lots of RAM)