When you assign an object of a derived class to an object of a base class, the derived class portion of the object gets sliced off.
So if you simply try to call the employee
base class operator=
function to copy the entire employee
portion of the object, the derived class portion will be lost. This is why you need to downcast the other
object to a const basepluscommissionemployee&
to preserve the derived class portion of the object.
dynamic_cast
is the appropriate way to perform a downcast when you need to access the derived class portion of an object that is pointed to by a base class pointer or reference. It checks at runtime whether the object can be safely cast to the desired derived class type, and returns a null pointer or throws a std::bad_cast
exception if the cast is not valid.
If you don’t want to use dynamic_cast
, you could consider using a virtual clone function to create a copy of the object that is of the correct derived class type. Here’s an example implementation:
class employee {
public:
virtual employee* clone() const {
return new employee(*this);
}
virtual employee& operator=(const employee& other) {
if (this != &other) {
// copy employee portion of object
}
return *this;
}
};
class basepluscommissionemployee : public employee {
public:
virtual basepluscommissionemployee* clone() const override {
return new basepluscommissionemployee(*this);
}
virtual basepluscommissionemployee& operator=(const employee& other) override {
const basepluscommissionemployee* rhs = dynamic_cast<const basepluscommissionemployee*>(other.clone());
if (this != rhs) {
// copy basepluscommissionemployee portion of object
employee::operator=(other); // copy employee portion of object
}
delete rhs;
return *this;
}
};
In this implementation, both the employee
base class and the basepluscommissionemployee
derived class have a virtual clone
function that creates a new copy of the object. The basepluscommissionemployee
operator=
function calls the clone
function of the other
object to create a new copy that is of the correct derived class type. Then, the basepluscommissionemployee
portion of the object is copied over, followed by a call to the employee
base class operator=
function to copy over the employee
portion of the object. Finally, the cloned object is deleted.
This approach avoids using dynamic_cast
, but it requires a virtual clone
function to be implemented in both the base and derived classes, which may not always be desirable or feasible.