크리에이티브 커먼즈 라이선스
Creative Commons License

(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;
}

신고
Posted by simon_ryu
TAG


티스토리 툴바