Assigning base class members in a copy assignment statement

I have a class that inherits from the MSFT class and therefore cannot be changed, and I would like my derived class to have the same behavior for its copy constructor and copy assignment operator. The problem that I encountered is that in the copy constructor you can call the constructor for the base class in the list of initializers, but in this case this is not an option. How can I correctly recreate this behavior in an assignment statement? Is it enough to just call the base class constructor in the operator overload body?

Additional note: the base class inherits from CObject, which has the = () operator and copy constructor as private and unrealized methods, so, unfortunately, any calls with them will lead to a compilation error.

The following is a simplified code script:

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 member functions of a class:

 // 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 note on CObject

+4
source share
2 answers

In the general case, you do this either by explicitly calling the operator = for a base class subobject, or using the copy and exchange idiom, if available:

 //explicit call to base operator= Derived& operator=(const Derived& rhs) { Base::operator=(rhs); // derivedInt = rhs.derivedInt; return *this; } //or copy&swap: Derived& operator=(const Derived& rhs) { Derived tmp(rhs); //copy tmp.swap(*this); return *this; } void swap(Derived& other) { Base::swap(other); std::swap(derivedInt,other.derivedInt); } 

Update: since your base class is not intended for copying, your derived class also should not be assigned for copying. There are some cases where classes contain non-copyable parts, but are perfectly copyable. In those cases, the uncomplicated part is that which does not directly affect the state of class objects, for example. unique identificator. Then these parts will usually not be changed during the appointment. However, in those cases the parts not subject to copying should not be kept by inheritance, but rather by aggregation.

It is briefly said: Iheritance means the relationship "is-A". Your database cannot be copied. Your derivative is the base. Therefore, your Derived cannot be copied.

+5
source

Like this

 Derived& operator=(const Derived& rhs) { Base::operator=(rhs); derivedInt = rhs.derivedInt; return *this; } 
+2
source

All Articles