I've got a class that inherits from a MSFT class, and therefore cannot be changed, and I'd like my derived class to have identical behavior for its copy constructor and copy assignment operator. The trouble I'm having is that in the copy constructor, you are free to invoke a constructor for the base class in the initializer list, but in the operator, this is not an option. How can I properly recreate this behavior in the assignment operator? Is it sufficient to just call the base class's constructor in the body of the operator overload?
Additional note: the base class inherits from CObject, which has operator=() and the copy constructor as private and unimplemented methods, so unfortunately any calls to those will result in a compile error.
I've provided a simplified code scenario below:
Class declarations:
class Base
{
protected:
int baseInt;
public:
Base(int);
}
class Derived : public Base
{
public:
Derived(const Derived& other);
Derived& operator=(const Derived& rhs);
private:
int derivedInt;
}
Derived class member functions:
// Copy Constructor
Derived(const Derived& other) : Base(5)
{
derivedInt = other.derivedInt;
}
// Copy Assignment Operator
Derived& operator=(const Derived& rhs)
{
if (&rhs != this)
{
derivedInt = other.derivedInt;
return *this;
}
}
EDIT: Updated syntax and added CObject note
Base(5);just creates a temporaryBaseobject and then immediately destroys it... - Oliver Charlesworth