(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;
}
'IT' 카테고리의 다른 글
R (0) | 2014.07.02 |
---|---|
Maple 강의자료 (0) | 2009.04.10 |
국내 아키텍트 평균 연봉은 6450만원 (0) | 2009.02.17 |
Friend functions and classes (0) | 2008.09.03 |
Virtual function with parameter types different from those of a base class (0) | 2008.08.28 |