1

I'd be grateful if someone could double-check this for me and confirm it sounds alright.

class P {
protected:
    float p();

public:
    virtual float compute() { return p(); };
};

class PI : virtual public P {
protected:
    float i();

public:
    float compute() { return p() + i(); };
};

class PD : virtual public P {
protected:
    float d();

public:
    float compute() { return p() + d(); };
};

class PID : public PI, public PD {
public:
    float compute() { return p() + i() + d(); };
};

Update(1): Made the sample more coherent, for future generations.

Update(2): Alright one last push before we seal this off; does P::compute() need to be virtual ?

Update(3): Change of plan, how would I achieve this

Controller<PD> p;

or

Controller<PID> pid;

Thanks everyone!

k4my4b
  • 29
  • 4
  • Might want to expand on what “PID” is (un-acronym-izing and/or using accessible real-world examples) and otherwise focus on a specific concern that might exist. – user2864740 May 09 '20 at 18:34
  • 1
    What do you want us to confirm? It doesn't do anything useful, so if it compiles, it's correct, right? – HolyBlackCat May 09 '20 at 18:34
  • Are you asking about diamond problem? https://stackoverflow.com/questions/2659116/how-does-virtual-inheritance-solve-the-diamond-multiple-inheritance-ambiguit – orhtej2 May 09 '20 at 18:44
  • 1
    Can't say without more context. Correct syntax does not imply correct code. – user4581301 May 09 '20 at 18:50
  • What makes you think something might be wrong? – JaMiT May 09 '20 at 19:20

1 Answers1

4

If your question should be interpreted as "does it make sense to use this hierarchy to implement proportional, proportional-integral, proportional-derivative and proportional-integral-derivative controller" then my answer is:

OOP implementation (in C++ or in whatever else) doesn't really model real world.

For example, if square is refinement of rectangle and rhombus, which are both refinements of parallelogram, making square inherit from rhombus and rectangle will violate Liskov Substitution Principle.

See What is an example of the Liskov Substitution Principle? for more details.

So, back from square to P/PI/PD/PID - depending on what exactly you are trying to achieve, the model may or may not work.

Otherwise I agree with other the answer and comments that this looks like valid C++.

copmute is implicitly overridden by each of derived classes, yet you may want to mark each overridden compute with override keyword.

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79