Reputation: 75629
Consider the following short program.
#include <string>
int main(){
std::string hello("HelloWorld");
std::string& helloRef(hello); // "line 2"
std::string& hello3 = hello; // "line 3"
}
Are line 2 and line 3 equivalent?
I have tried various searches like "constructor reference" and "reference copy constructor" but I cannot seem to find documentation on line 2.
Upvotes: 3
Views: 103
Reputation: 11
#include <string>
int main(){
std::string hello("HelloWorld");
std::string& helloRef(hello);
std::string& hello3 = hello;
}
In the above code,
by line number 1, invokes single parameter constructor in predefined string class and creates the object hello by initializing the string "HelloWorld".
By line number 2, invokes copy constructor in predefined string class and creates the object helloRef by initializing the same string of object hello. Because of the" &" symbol used, helloRef will act as an reference object to hello object.
By line number 3, it is an syntax for creating reference variable for an existing variable. Hence by this declaration hello3 reference object will be created for hello object. Here because of "=" operator, invokes predefined method in string class that is = operator overloaded function and initializes the string to hello3 object.
Here reference variable or reference object means,
Just creating an alias name to the same memory location.
Upvotes: 1
Reputation: 359
Yes, helloRef and hello3 will both be references to the hello string object. This is called reference initialization. Typically you would use the = operator here. You would use the 2nd line's form in the constructor initialization list of a class, like this:
class c
{
public:
c()
: hello("HelloWorld"),
helloRef(hello)
{
std::string& hello3 = hello;
}
private:
std::string hello;
std::string& helloRef;
};
More info: http://en.cppreference.com/w/cpp/language/reference_initialization
Upvotes: 3