0
class Cell : public QTableWidgetItem
{
public:
    Cell();

    QTableWidgetItem *clone() const;
...
}

Above is the class definition in a Qt program. Below is the rest part.

QTableWidgetItem *Cell::clone() const
{
    return new Cell(*this);
}

My question is about the last sentence, if I change it to like:

return new Cell(this);

Then Qt will give error message: enter image description here

Why? I understand that this is a pointer, and cannot be the argument. But *this could be a & type?

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85
Tom Xue
  • 3,169
  • 7
  • 40
  • 77
  • 5
    Because `*this*` is a `Cell`. Passing a `Cell` as an actual parameter to a function that takes a `Cell&` as its formal parameter is perfectly fine in C++ and will pass that parameter by reference. It's analogous to how you'd initialize a reference variable. – Michael Mar 16 '13 at 08:07
  • Thank you for this good explaination! – Tom Xue Mar 16 '13 at 08:20
  • @Michael Your excellent comment missed the "Your Answer" box by a few inches. Better luck next time! – Cody Gray - on strike Mar 16 '13 at 08:21

1 Answers1

5

Since you haven't defined a copy constructor for your class, the compiler generates one for you with the following signature: Cell(const Cell&) (read more here: Conditions for automatic generation of default/copy/move ctor and copy/move assignment operator?). When you try to invoke Cell(this), the compiler attempts to find Cell(Cell*) among the various Cell constructors - obviously none matches. Cell(*this) matches the auto-generated copy constructor Cell(const Cell&) since it expects a reference to an object of type Cell as a parameter (not a pointer to it), and *this dereferences the pointer so the actual object can be passed by reference. As far as the calling syntax considered, the invokation of Cell(*this) can be resolved by the compiler as passing by reference or as passing by value. Since in your case the copy constructor receives the parameter by reference (due to the & in the signature), the compiler will resolve the Cell(*this) as pass-by-reference (actually it must be by reference, but that's another story). Read more about the subject here: What's the difference between passing by reference vs. passing by value?

Community
  • 1
  • 1
SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85