Cristi
Cristi

Reputation: 730

Copy assignment operator for derived class

I have a class B deriving from A. A implements copy constructor and assignment operator. I have copy constructor for B and want to implement assignment for B. My approach (most likely incorrect) is

B& B::operator=(const B& other) {
    B tmp (other);
    std::swap <A>(*this, tmp);
    std::swap (m_member, other.m_member);
}

Can something like this work? I have looked on the web for specializations of std::swap to a basis class but have not found something usefull.

Upvotes: 1

Views: 771

Answers (1)

Noel Lopes
Noel Lopes

Reputation: 106

You can check this stackoverflow thread (calling operators of base class... safe?) on how to use operator = from base class.

What I don't understand is why you are using swap. You should instead do something like this:

B& B::operator=(const B& other) {
    A::operator = (other);
    this->m_member = other.m_member;
    return *this;
}

Upvotes: 1

Related Questions