Abstract class, copy constructor

13,907

Solution 1

If it has only pure virtual methods (and no data members) then, no, the synthesised one is fine (and won't do anything).

If it does have data members then you should define your own copy constructor if/when it makes sense to do so, just like for any other class. Derived classes don't really have much to do with it.

Solution 2

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

Solution 3

If it is an object you plan on copying, yes, it's a good idea. See my comment below for when it isn't.

If your virtual base class relies on resources that need to be explicitly allocated and copied (buffers, operating system objects, etc.), defining a copy constructor saves you the trouble of doing so in every derived class separately (and, additionally, is something you couldn't do if those base resources were private, using public inheritance).

E.g.:

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...
}
Share:
13,907

Related videos on Youtube

Johny
Author by

Johny

Updated on June 04, 2022

Comments

  • Johny
    Johny almost 2 years

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

  • janhink
    janhink about 13 years
    I would just add that a copy constructor should be used in favor of overriding the = operator. It improves readability and is less error-prone.
  • Nate
    Nate about 13 years
    I honestly prefer to declare private empty copy constructors and assignment operators to everything. This way, if I ever try to copy something inappropriately, the compiler complains. Only if I really actually need a copyable object do I expose any of that. You might laugh reading that, but you'd be surprised how many problems were fixed when I started that practice. ;)
  • Erik Aronesty
    Erik Aronesty about 4 years
    @nate or you can use = delete

Related