Quantcast
Channel: User HolyBlackCat - Stack Overflow
Viewing all articles
Browse latest Browse all 1266

Answer by HolyBlackCat for Redefining swap function in inherited classes?

$
0
0

Since the derived class doesn't add any fields, it shouldn't provide a custom swap at all. The one from the base class will be used automatically.

If it did have extra members, the swap should've been implemented as:

using std::swap;swap(static_cast<user &>(first), static_cast<user &>(second));swap(first.extra, second.extra); // Only swap the fields added in the derived class.

Some other things:

  • Move constructor, copy&swap operator=, and swap() all should be noexcept.
  • Unless you're doing this for practice, you should follow the rule of 0 and get rid of all those custom copy/move constructors, assignment operators, and swap(). The implicitly generated ones will work just fine.
  • Setters should accept parameters by value, then std::move them.
  • Might be a good idea to get into the habit of writing using std::swap; swap(...); instead of calling std::swap directly, to be able to utilize custom swap without having to think whether you need to omit std:: or not for each individual type.

Viewing all articles
Browse latest Browse all 1266

Trending Articles