I know that for freestanding classes, you should avoid calling the assignment operator in your copy constructor. Copy and swap and moving the reused code to a private member function are two ways to easily reuse code. However, recently I ran into a bit of a problem. Here's the code:
// Derived.h
class Derived : Base {
// bunch of fun stuff here
// ...
// constructor that builds a derived object from a base one
explicit Derived(const Base& base);
// Assignment operator for moving base class member variables into the derived one
Derived& operator=(const Base& base);
};
// Derived.cpp
Derived::Derived(const& Base base) {
*this = base; // use assignment operator from derived to base
}
Derived& Derived::operator=(const Base& base) {
static_cast<Base>(*this) = base; // call base class assignment operator
}
In this given application, this all actually makes sense, because the derived class can now perform operations on the members it just received from the base class to fill in the rest of the object. Also, this provides a safe way for the user to convert a base object to a derived object. What I seem to be missing is whether or not such code is good code practice, or if there is an easier/better way to accomplish what I am trying to do? As I mentioned before, I know it's generally a no-go to call the assignment operator from a copy constructor in a freestanding class, but what about calling the assignment operator from another constructor?