Search code examples
c++inheritancevirtual-functions

Inheritance, overriding, and virtual functions to avoid repeated code


I have three classes, A, B, and C. B and C are derived from A. Both B and C need to implement a method F. The code in B.F() is a subset of C.F().

  1. Is it a good way declare A.F() as a virtual function and define B.F() and C.F()? There would be the same code in 2 methods, which I would like to avoid. What are the other possibilities?
  2. Define A.F() with the common code and override it in C.F(). While overriding how can the output of A.F() be used in C.F(), so that repeated code can be avoided?

Solution

    1. I guess it's not the best thing to do. If you can avoid code rewriting - sure, do it.

    2. It would be better to define F() in A, as you've said, with the common code for both B and C, and then override it in C.F(), using A::F() call in overriden function. I mean, with this you can firstly execute parent method A.F(), and then go with new extra logic. If you're inheriting B from A, you shouldn't then bother about this method in B at all.

    Note that from this point of view, the order will be important. If you want parent code execution to be first, then call A::F() before your additional logic. It's on you to decide, what order to choose, though.

    EDIT

    I will add a link with a good example for you, if you don't know how to call parent method code inside child method. Take a look, and have a nice time.