I want to know the meaning of & in the example below:
class1 &class1::instance(){
///something to do
}
The & operator has three meanings in C++.
"Bitwise AND", e.g. 2 & 1 == 3
"Address-of", e.g.: int x = 3; int* ptr = &x;
Reference type modifier, e.g. int x = 3; int& ref = x;
Here you have a reference type modifier. Your function class1 &class1::instance() is a member function of type class1 called instance, that returns a reference-to-class1. You can see this more clearly if you write class1& class1::instance() (which is equivalent to your compiler).
This means your method returns a reference to a method1 object. A reference is just like a pointer in that it refers to the object rather than being a copy of it, but the difference with a pointer is that references:
can never be undefined / NULL
you can't do pointer arithmetic with them
So they are a sort of light, safer version of pointers.
Its a reference (not using pointer arithmetic to achieve it) to an object.
It returns a reference to an object of the type on which it was defined.
In the context of the statement it looks like it would be returning a reference to the class in which is was defined. I suspect in the "Do Stuff" section is a
return *this;
It means that the variable it is not the variable itself, but a reference to it. Therefore in case of its value change, you will see it straight away if you use a print statement to see it. Have a look on references and pointers to get a more detailed answer, but basecally it means a reference to the variable or object...
Related
The topic is pretty much in the title of the question. I saw this in Meyrses book "Effective C++":
the fact that C++ returns objects by value
What does that mean and how the C++ standard supports that message? For instanance, say that we have something like this:
int foo()
{
int a = 1;
return a;
}
That's pretty clear, the phrase would mean that we returns the copy of the value stored in the local variable. But consider this:
int& foo()
{
int a = 1;
return a;
}
A compiler should warn us about returning a reference to a local variable. How does that "returning by value fact" apply to that example?
Meyers is correct in the main, though you have to take that wording with a pinch of salt when dealing with references. At a certain level of abstraction, here you're passing the reference itself "by value".
But what he's really trying to say is that, beyond that, C++ passes by value by default, and that this contrasts with languages such as Java in which objects are always chucked around with reference semantics instead.
In fact, one could argue that the passage doesn't apply to your code at all, because the reference is not an "object".
When the book says that "C++ returns objects by value", it explains what happens when you use a "plain" class name as the return type without additional "decorations", such as ampersands or asterisks, e.g.
struct MyType {
... // Some members go here
};
MyType foo() {
...
}
In the example above foo() returns an object by value.
This quote should not suggest that C++ lacks other ways of returning data from a function: as you can easily construct a function that returns a reference or a pointer.
Note that returning an object by pointer or by reference creates undefined behavior only when you return a pointer or a reference to a local object. Accessing object past its lifetime always causes undefined behavior. Returning a local by reference or by pointer is perhaps the most common mistake that causes this undefined behavior.
Return by reference will give you a error as u are passing a reference of a variable to another function ( function which called function foo) which is beyond the scope of that local variable ( variable a).
Sorry for turning to here for such a basic question, but can someone just quickly clear this up for me? I'll then delete the thread so as not to cause noob clutter.
In the following example from the C++ Primer Plus text, doesn't the & operator in the function declaration designate that the function returns a pointer to a Stock object? Why then does the function proceed to return the s and this objects by value instead?
"...What you want to return, however, is not this, because this is the address of the object. You want to return the object itself, and that is symbolized by *this. (Recall that applying the dereferencing operator * to a pointer yields the value to which the pointer points.) Now you can complete the method definition by using *this as an alias for the invoking object."
const Stock & Stock::topval(const Stock & s) const {
if (s.total_val > total_val)
return s; // argument object
else
return *this; // invoking object
}
Yeah, that's confusing. C++ massively overloads every symbol, because there just aren't enough symbols on the keyboard.
The ampersand & is used for two different meanings which are conceptually similar, but are actually completely different language features.
Meaning 1: Reference type declaration. Append an ampersand to type A which means a-reference-to-type-A. Example:
Stock x;
Stock& s = x; // now s is a reference to x
Meaning 2: Address-of operator. A unary operator that returns a pointer to its argument. Example:
Stock x;
Stock* s = &x; // now s a pointer to x
Reminder: References and pointers are exactly the same thing, except they have different syntax, and references can never be null, and you can't have a reference to a reference.
Don't delete this thread, we love n00bs. I'm a n00b myself.
const Stock & means return a const reference to an object. A pointer to an object would be const Stock *. Don't mix the two! So the this pointer is being dereferenced and returned.
I'm currently reading through Accelerated C++ and I realized I don't really understand how & works in function signatures.
int* ptr=#
means that ptr now holds the address to num, but what does that mean?
void DoSomething(string& str)
from what I understand that is a pass by reference of a variable (which means passing the address) but when I do
void DoSomething(string& str)
{
string copy=str;
}
what it creates is a copy of str. What I thought it would do is raise an error since I'm trying to assign a pointer to a variable.
What is happening here? And what is the meaning of using * and & in function calls?
A reference is not a pointer, they're different although they serve similar purpose.
You can think of a reference as an alias to another variable, i.e. the second variable having the same address. It doesn't contain address itself, it just references the same portion of memory as the variable it's initialized from.
So
string s = "Hello, wordl";
string* p = &s; // Here you get an address of s
string& r = s; // Here, r is a reference to s
s = "Hello, world"; // corrected
assert( s == *p ); // this should be familiar to you, dereferencing a pointer
assert( s == r ); // this will always be true, they are twins, or the same thing rather
string copy1 = *p; // this is to make a copy using a pointer
string copy = r; // this is what you saw, hope now you understand it better.
The & character in C++ is dual purpose. It can mean (at least)
Take the address of a value
Declare a reference to a type
The use you're referring to in the function signature is an instance of #2. The parameter string& str is a reference to a string instance. This is not just limited to function signatures, it can occur in method bodies as well.
void Example() {
string s1 = "example";
string& s2 = s1; // s2 is now a reference to s1
}
I would recommend checking out the C++ FAQ entry on references as it's a good introduction to them.
https://isocpp.org/wiki/faq/references
You shouldn't know anything about pointers until you get to chapter 10 of Accelerated C++ !
A reference creates another name, an alias, for something that exists elsewhere. That's it. There are no hidden pointers or addresses involved. Don't look behind the curtain!
Think of a guy named Robert
guy Robert;
Sometimes you may want to call him Bob
guy& Bob = Robert;
Now Bob and Robert both refer to the same guy. You don't get his address (or phone number), just another name for the same thing.
In your function
void DoSomething(string& str)
{
string copy=str;
}
it works exactly the same, str is another name for some string that exists somewhere else.
Don't bother with how that happens, just think of a reference as a name for some object.
The compiler has to figure out how to connect the names, you don't have to.
In the case of assigning variables (ie, int* ptr = &value), using the ampersand will return the address of your variable (in this case, address of value).
In function parameters, using the ampersand means you're passing access, or reference, to the same physical area in memory of the variable (if you don't use it, a copy is sent instead). If you use an asterisk as part of the parameter, you're specifying that you're passing a variable pointer, which will achieve almost the same thing. The difference here is that with an ampersand you'll have direct access to the variable via the name, but if you pass a pointer, you'll have to deference that pointer to get and manipulate the actual value:
void increase1(int &value) {
value++;
}
void increase2(int *value) {
(*value)++;
}
void increase3(int value) {
value++;
}
Note that increase3 does nothing to the original value you pass it because only a copy is sent:
int main() {
int number = 5;
increase1(number);
increase2(&number);
increase3(number);
return 0;
}
The value of number at the end of the 3 function calls is 7, not 8.
It's a reference which allows the function to modify the passed string, unlike a normal string parameter where modification would not affect the string passed to the function.
You will often see a parameter of type const string& which is done for performance purposes as a reference internally doesn't create a copy of the string.
int* ptr=#
1st case: Since ptr is a memory and it stores the address of a variable. The & operator returns the address of num in memory.
void DoSomething(string& str)
2nd case: The ampersand operator is used to show that the variable is being passed by reference and can be changed by the function.
So Basically the & operator has 2 functions depending on the context.
While pass by reference may be implemented by the compiler by passing the address as a pointer, semantically it has nothing to do with addresses or pointers. in simple terms it is merely an alias for a variable.
C++ has a lot of cases where syntax is reused in different contexts with different semantics and this is one of those cases.
In the case of:
int* ptr=#
you are declaring a variable named ptr with a type of an int * (int pointer), and setting its value to the "address of the variable num" (&num). The "addressof" operator (&) returns a pointer.
In the case of:
void DoSomething(string& str)
you are declaring the first parameter of the DoSomething() method to be of type "reference to string". Effectively, this is the C++ way of defining "pass-by-reference".
Note that while the & operator operates similarly in these cases, it's not acting in the same way. Specifically, when used as an operator, you're telling the compiler to take the address of the variable specified; when used in a method signature, you're telling the compiler that the argument is a reference. And note as well, that the "argument as a reference" bit is different from having an argument that is a pointer; the reference argument (&) gets dereferenced automatically, and there's never any exposure to the method as to where the underlying data is stored; with a pointer argument, you're still passing by reference, but you're exposing to the method where the variable is stored, and potentially exposing problems if the method fails to do a dereference (which happens more often than you might think).
You're inexplicitly copy-constructing copy from str. Yes, str is a reference, but that doesn't mean you can't construct another object from it. In c++, the & operator means one of 3 things -
When you're defining a normal reference variable, you create an alias for an object.
When you use it in a function paramater, it is passed by reference - you are also making an alias of an object, as apposed to a copy. You don't notice any difference in this case, because it basically is the object you passed to it. It does make a difference when the objects you pass contain pointers etc.
The last (and mostly irrelevent to your case) meaning of & is the bitwise AND.
Another way to think about a reference (albeit slightly incorrect) is syntactic sugar for a dereferenced pointer.
I have a method:
odp(foo& bar);
I'm trying to call it:
foo baz;
odp(&baz);
I get a compiler error:
error C2664: "odp" cannot convert parameter 1 from 'foo *' to 'foo &'
What am I doing wrong? Aren't I passing in a reference to baz?
UPDATE: Perhaps I have a misconception about the relationship between pointers and references. I thought that they were the same, except references couldn't be null. Is that incorrect?
When you apply the unary & operator to an object, you get a pointer to that object, not a reference. You need a reference in this case. In order to initialize a reference parameter, you don't need to apply any operators at all: an lvalue object can immediately be used by itself to initialize a reference of the appropriate type.
The informal synonymity between the notions of "pointer" and "reference" (as in "pass by pointer" and "pass by reference") is specific to C language. But in C++ they mean two completely different things.
The odp function need a reference to a foo var whereas you are passing the adress of a foo var (pointer).
Just pass baz like:
foo baz;
opd(baz);
And it will compile.
No, you're passing a pointer to baz. Drop the &.
When you use &baz, you are actually saying address of baz, so you are passing a pointer.
References and pointers are NOT the same in C++ - although you have probably read that most compilers implement references using pointers at the machine-code level. You don't need to care how they are implemented by the compiler - but what the semantics of a "reference" and a "pointer" are in C++.
int i = 5;
int &j = i; // j refers to the variable i
// wherever the code uses j, it actually uses i
j++; // I just changed i from 5 to 6
int *pj = &i; // pj is a pointer to i
(*pj)--; // I just changed i back to 5
Note that I can change pj to point to another integer, but I cannot change the reference j to refer to another integer.
int k = 10;
pj = &k; // pj now actually points to k
(*pj)++; // I just changed k to 11
j = k; // no, this doesn't change the reference j to refer to k instead of i,
// but this statement just assigned k to i, that is, i now equals 11!
In C++, references are aliases, not addresses. You can, for instance, have multiple names for a single pointer, just as you might have multiple names for a single real object.
When you declare a function taking a reference parameter, the function will automatically alias whatever variable you pass to it. Whatever it aliases, though, must be of the same type as the reference. In your case, you are aliasing an int* with an int reference, which doesn't make sense.
Maybe you're being misled by old C conventions? In C, you "pass by reference" by creating a pointer, because the language doesn't have references - you use the pointer to "reference" the original variable. In C++, references are supported by the language and there's no need to create a pointer to the variable when you call the function.
foo baz;
odp(baz);
What does address operator mean.
say in the method below.
what should be passed in the method as parameter value of integer or the address of an integer variable.
void func1(int&)// method declaration
void func1(int& inNumber)//method definition
{
//some code
}
That’s not the address operator – it’s the reference type character. This means that for any type T, T& is a reference to T. It’s an unlucky coincidence that this happens to be the same character as the address operator.
You can pass normal objects to this method. No need to take any further action. Read up on references in your favourite C++ book.
There is no address-of operator in your code - the ampersand is being used to declare a reference. Which C++ text book are you using that does not cover this?
In this case the function takes a reference to an int which is denoted by the int &inNumber.
The function is called as if you were calling it with the value:
int x = 2;
func1(x);
From the perspective of the caller, this looks exactly the same as a pass by value function, though in the case of the reference the function may indeed change the value of x.
That's not an address operator. In a declaration, the & means it's a reference.
You can think of references as pointers that you don't have to dereference.* You can just say inNumber = 5; (instead of *inNumber = 5;) and the effect will be visible outside the function.
* Note: References are not just "pointers that you don't have to dereference". It just helps to think of them in that way, sometimes.
its called as reference in c++
http://en.wikipedia.org/wiki/Reference_(C%2B%2B)