Michael Michael - 1 month ago 8
C++ Question

Reinitialize all member variables in derived class only

I have two classes:

class NonCopyable {
private:
int key;
protected:
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator = (const NonCopyable &) = delete;
};

class Derived : public NonCopyable {
private:
std::vector<int> numbers;
float f;
int* ptr;
public:
Derived() : f(5.0f), ptr(nullptr) {}
~Derived();
};


Now, I'd like to reinitialize all the values in the Derived class and call the appropriate destructors. That is, the NonCopyable class should not be touched, but the Derived class should be changed as if it was newly initialized.

What is the simplest way of achieving this goal? I am trying to avoid making a member function which manually reinitializes every member variable.




Clearly, I can not use the following approach:

Derived d;
// [...] many changes to d
d = Derived();


because the copy constructor is deleted from the NonCopyable class and the fact that it would change the member variables of NonCopyable had this not been the case.

Answer

It becomes much easier if you move your private data to a separate aggregate:

struct DerivedData {
    std::vector<int> numbers;
    float f = 5.0;
    int* ptr = nullptr;
};

class Derived : public NonCopyable {
    DerivedData data;
public:
    ~Derived();
    void reset() { data = DerivedData(); }
};
Comments