I have an abstract base class that enforces certain operations on all derived classes. In addition to this, I would like to enforce certain other operations that are specific to subclasses declared in the derived classes.
The following is a minimal example:
class Base {
public:
virtual void init() = 0;
virtual void reset() = 0;
};
class Derived1 : public Base {
class Data {
int *x1;
public:
Data() {
x1 = NULL;
}
void alloc(int num) {
x1 = new int[num];
}
~Data() {
delete[] x1;
x1 = NULL;
}
} data;
public:
void init() { ... }
void reset() { ... }
void resetData() {
data.~Data();
}
};
class Derived2 : public Base {
class Data {
float *x2;
public:
Data() {
x2 = NULL;
}
void alloc(int num) {
x2 = new float[num];
}
~Data() {
delete[] x2;
x2 = NULL;
}
} data;
public:
void init() { ... }
void reset() { ... }
void resetData() {
data.~Data();
}
};
In the example above Base enforces the init() and reset() methods on all derived classes.
In addition to this I would like to enforce that all derived classed have
- a member variable of named data and
- a method called
resetData()that calls the destructor on this variable - a method called
Data &getData()that gets a reference to the variable
What would be the best way to achieve this?
Thanks for your responses. This is what I have come up with. I know I am breaking my original requirements i.e. Data must be a subclass of the derived classes, but the following design pattern ensures that all derived classes have a
datamember variable, each of a different type, but again, each of these have some basic methods enforced on them. I think this is what @emsr suggested in one of his comments.Also now
resetData()is done in a separate method. Thanks to @LuchianGrigore for pointing out a possible problem with explicitly calling the destructor. Now this method explicitly instead. The virtual destructor will also call the same function. I know that I shouldn’t call virtual functions from a destructor but by setting the scope of the function explicitly, I hope I am avoiding any ambiguity here. (Or is this also a problem?)