Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Reference constructor syntax

Tags:

c++

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?

  • If so, can someone please provide documentation on the line 2 syntax?
  • If not, can someone explain the difference?

I have tried various searches like "constructor reference" and "reference copy constructor" but I cannot seem to find documentation on line 2.

like image 293
merlin2011 Avatar asked Jun 02 '26 21:06

merlin2011


2 Answers

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

like image 63
coderkevin Avatar answered Jun 05 '26 10:06

coderkevin


#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.

like image 45
user3587705 Avatar answered Jun 05 '26 11:06

user3587705



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!