Abstract class, copy constructor

Does it make sense to define constructor / operator = in a class that has a pure virtual method or only in derived classes?

+4
source share
5 answers

like ordinary classes: yes, if you have a specific need for implementation.

+5
source

If it has only pure virtual methods (and there are no data elements), then no, one of them is synthesized (and will do nothing).

If it has data members, then you should define your own copy constructor, if / when it makes sense to do this, as for any other class. Derived classes actually have nothing to do with this.

+4
source

If this is the object you are planning to copy, yes, it is a good idea. See my comment below if this is not the case.

If your virtual base class uses resources that must be explicitly allocated and copied (buffers, operating system objects, etc.), the definition of a copy constructor will save you from having to do this in each derived class separately (and, in addition, then you will not could do if these underlying resources were private using public inheritance).

eg:.

class Base { public: Base( const Base & ); virtual ~Base(); virtual void Method() = 0; // etc... private: int *memberIntArray; int length; // etc... }; class DerivedOne : public Base{ public: DerivedOne( const DerivedOne & ); virtual ~DerivedOne(); virtual void Method(); // etc... protected: // data, etc... }; class DerivedTwo : public Base{ public: DerivedTwo( const DerivedTwo & ); virtual ~DerivedTwo(); virtual void Method(); // etc... protected: // data, etc... }; /////////////////// Base::Base( const Base & other ) { this->length = other.length; this->memberIntArray = new int[length]; memcpy(this->memberIntArray,other.memberIntArray,length); } //etc... DerivedOne::DerivedOne( const DerivedOne & other ) : Base( other ) { //etc... } DerivedTwo::DerivedTwo( const DerivedTwo & other ) : Base( other ) { //etc... } 
+2
source

Yes you should.
The rules for having your own implementations for the copy constructor, copy assignment operator, and destructor for the class will even apply to the abstract class.
Also, see Rule Three

0
source

It depends on your use if you are not doing anything that requires copying to process subtly, for example. copy descriptor. It would be better to define a copy constructor in derived classes, if necessary.

0
source

Source: https://habr.com/ru/post/1347219/


All Articles