2

Observe the following class:

class Object {
  public:
    Object() {}
    Object(const Object & other) = delete;
    void setName(const std::string & name) {
      this->name = name;
    }
    void printName() {
      std::cout << name << std::endl;
    }
  private:
    std::string name = "Janice";
};

Now observe this code:

int main() {
  Object o;
  Object p (o);
  return 0;
}

I understand that the previous code invokes the implicit copy constructor Object(const Object & other). Thus, if we delete the copy constructor we get an error:

// delete copy constructor
class Object {
  public:
    Object(const Object & other) = delete;

error: use of deleted function 'Object::Object(const Object&)'

But what if we change p to a reference?

int main() {
  Object o;
  Object & p (o);
  return 0;
}

The code compiles fine without a copy constructor or a warning. What is actually happening when we construct a reference with the parenthesis () syntax?

Is there any difference (neglible or not) between Object & p (o); and Object & p = o;?

1
  • There's also no difference between this code and Object p; Object &o(p); Commented Mar 18, 2014 at 8:32

3 Answers 3

2

What is actually happening when we construct a reference with the parenthesis () syntax?

The reference is initialised to refer to the result of the expression in parentheses.

Is there any difference (neglible or not) between Object & p (o); and Object & p = o;?

No. Quoting the standard (C++11 8.5/13):

The form of initialization (using parentheses or =) is generally insignificant, but does matter when the initializer or the entity being initialized has a class type

So it doesn't matter for a reference type. (For a class type, parentheses give direct initialisation via a constructor, while = gives copy initialisation via user-defined conversions).

Sign up to request clarification or add additional context in comments.

Comments

0

The type is Object&, which is a reference. p then is a reference, which, when initilized, will cause it to bind to the initializer.

You could test for it by comparing their addresses. Remember that two different objects cannot have the same address, but references, which are only aliases have the same address as the object it is referring to.

assert(&p == &o);   // p should refer to o

The initialization is the same as

Object& p = o;   // Still binds `o` to `p`

Comments

0

When you do this:

Object & p (o);

You're not constructing a new object, you just initialize a reference (i.e. you set the address of object it points to).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.