Search code examples
c++copy-constructorlvalueampersandaddressof

C++ copy constructor syntax: Is ampersand reference to r/l values?


The following is an excerpt from my C++ text, illustrating the syntax for declaring a class with a copy constructor.

class Student {
     int no;
     char* grade;
 public:
     Student();
     Student(int, const char*);
     Student(const Student&);
     ~Student();
     void display() const; 
 };

The copy constructor, as shown here:

Student(const Student&);

Has an ampersand after the parameter Student.

In C, and C++ as-well I believe, the ampersand character is used as a 'address of' operator for pointers. Of course, it is standard to use the & character before the pointer name, and the copy constructor uses it after, so I assume this is not the same operator.

Another use of the ampersand character I found, relates to Rvalues and Lvalues as seen here: http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html

My question is not about Rvalues and Lvalues, I just want to know why the & character is placed after parameter, and what this is called and if/why it is necessary.


Solution

  • C++ has reference type that does not exist in C. & is used to define such a type.

    int i = 10;
    int& iref = i;
    

    Here iref is a reference to i.

    Any changes made to i is visible through iref and any changes made to iref is visible through i.

    iref = 10; // Same as i = 10;
    i = 20;    // Same as iref = 20;
    

    The reference can be an lvalue reference or an rvalue reference. In the above example, iref is an lvalue reference.

    int&& rref = 10;
    

    Here rref is an rvalue reference.

    You can read more about rvalue references at http://en.cppreference.com/w/cpp/language/reference.