Sunday, 27 August 2017

C++ Inheritance of copy, move, swap, assignment and destructor? Which do I need



Let's say that I have two classes




Base manages some memory. It has working move, swap, assignment and destructor.
Derived does not add anything new that need need to be managed (no new memory allocations).



class Base
{
public:
Base();
Base(const Base& other);
friend void swap(Base& a, Base& b);
Base(Base&& other);


protected:
int** some2Darray;
int w, h;
};

class Derived : public Base
{
public:
Derived();

//...?
};


Do I need to implement all those functions in derived class for it to be good? How to reuse those functions from base class? I don't need to manage any more memory in this class.



How those function would look if I added member to Derived class? Should I totally rewrite all those functions or is there some way to use for example "copy" base class and just copy that one added member additionally in copy constructor?


Answer



You can inherit (edit: yeah, well this is not true inheritance, maybe this shall be noted explicitly) constructors since c++11. Via




class Derived : public Base
{
public:
Derived();
using Base::Base; // <-- this will import constructors
};


But this will not take care of any extras!




However, you do not need to copy code. You can just call parent functions.



E.g:



class Derived : public Base
{
int extra;
public:
Derived() : Base(), extra(42){};
Derived(const Derived& other) : Base(other) {extra = other.extra;};

void copy(const Derived& other);
friend void swap(Derived& a, Derived& b);
};

void Derived::copy(const Derived& other){
Base::copy(other);
extra = other.extra;
}



Also don't forget about virtual destructor.



EDIT:
For swap I would just cast derived instances to their bases to make compiler use the swap defined for parent type. Then swap extra stuff.



void swap(Derived& a, Derived& b){
swap(static_cast(a), static_cast(b));
swap(a.extra, b.extra);
}


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...