IT

Copy constructor and assignment operator of derived class

simon_ryu 2008. 7. 28. 17:39

(source: Effective C++, 2E | Item 16 by Scott Meyers)

class Derived: public Base {
public:
Derived(int initialValue)
: Base(initialValue), y(initialValue) {}
Derived(const Derived& rhs) // erroneous copy
: y(rhs.y) {} // constructor
private:
int y;
};

// correct copy constructor
class Derived: public Base {
public:
Derived(const Derived& rhs): Base(rhs), y(rhs.y) {}
...
};

// erroneous assignment operator
Derived& Derived::operator=(const Derived& rhs)
{
if (this == &rhs) return *this;

this->m_member = rhs.m_member; // assign to Derived's
// lone data member
return *this;
}

// correct assignment operator (type 1)
// erroneous assignment operator
Derived& Derived::operator=(const Derived& rhs)
{
if (this == &rhs) return *this;

Base::operator=(rhs); // call this->Base::operator=
this->m_member = rhs.m_member;
return *this;
}

// correct assignment operator (type 2)
// erroneous assignment operator
Derived& Derived::operator=(const Derived& rhs)
{
if (this == &rhs) return *this;

static_cast<Base&>(*this) = rhs; // some complier allows only this one
this->m_member = rhs.m_member;
return *this;
}