Search code examples
c++thisthis-pointer

I have come across some C++ code.Why we have to use *this in block instead of this?


I have the following code, and I'm wondering why it uses *this instead of this.

class Quotation
{
protected:
    int value;
    char* type;
public:
    virtual Quotation* clone()=0;

    char * getType()
    {
        return type;
    }

    int getValue()
    {
        return value;
    }
};


class bikeQuotation : public Quotation
{
public:
    bikeQuotation(int number)
    {
        value=number;
        type="BIKE";
    }

    Quotation * clone()
    {
        return new bikeQuotation(*this);  // <-- Here!
    }
};

Solution

  • this is a pointer to the object. The copy constructor requires a reference to the object. The way you convert a pointer to a reference is with the dereferencing * operator.