Reputation: 79
I have a base class and a couple of derived classes. The derived classes have common methods, for example an activate()
or an init()
which are implemented in slightly different ways. So, i make activate()
and init()
pure virtual.
Then, there are methods like doSomething()
that 90% of derived classes use in different ways. The other 10% do not need that function.
Is it a reasonable practice to inherit doSomething()
like the following?
The base class:
class base {
public:
virtual void activate() = 0;
virtual void init() = 0;
virtual void doSomething(){ /* internal log that the function is not implemented */ };
};
And the derived classes:
class derivedA: public base {
public:
virtual void activate() override { /* activate A */ };
virtual void init() override { /* init A */ };
virtual void doSomething() override { /* do something in A */ };
};
//class derivedB to class derivedI like class derivedA
class derivedJ: public base {
public:
virtual void activate() override { /* activate J */ };
virtual void init() override { /* init J */ };
// doSomething() is not overriden and the implementation of base is used
};
Is this a possible way to do it or is there maybe a problem with the modelling?
Upvotes: 2
Views: 2119
Reputation: 101
If at least one class derived from base
does not need, conceptually, to implement doSomething()
, then doSomething()
should not be part of base
's interface, and so it needs to go into another interface.
That is, doSomething()
should be part of another abstract base class, call it base2
.
If doSomething()
could (or should) not be used separately from activate()
and init()
, derive base2
from base
and derive derivedA
toderivedI
from base2
, and derivedJ
from base
.
If it could, leave base2
it as a separate class and derive derivedA
toderivedI
from both base
and base2
, and only derive derivedJ
from base
.
Upvotes: 0
Reputation: 73444
is there maybe a problem with the modelling?
Definitely!
I expect that since derivedJ
inherits from base
, then doSomething()
is meant to be used (it doesn't matter which implementation).
However, you want your derivedJ
class to not provide this method, thus you should change your modelling.
A naive solution would be to modify your base
class, removing that function, like this:
class base {
public:
virtual void activate() = 0;
virtual void init() = 0;
};
Upvotes: 3