Search code examples
c++inversion-of-controlpure-virtual

Pros and cons for pure virtual c++ coding


I'm coming form java background, had a conversation today with one of our C++ developer regarding to convert an existing code to have a pure virtual methods (interface) and to use them as dependency injection all over the code for better decoupling.

He tried to convince me that we should use them only when there is a "logic" in the code and in case the code is just collecting information from the PC it is not necessary.

Long story short, I'm looking for good reasons why to refactor the code and use IoC and pure virtual method instead of leaving the working coupled code as is.


Solution

  • Why use pure-virtual methods?

    I try to write base class functions to provide default behaviour for all the interface methods. I am surprised by how often these defaults simply generate some error handling (using the locally accepted mechanism).

    For one example, I worked on code that received commands to set led states. During development, the 'other software' sometimes would (mistakenly) request a colour explicitly dis-allowed by the requirements. ('Red' disallowed on status led 5) My default functions generated the appropriate error message, and identified which 'other software' sent the erroneous request.


    There are also cases that in some way have no appropriate default behaviour. For these situations, I create pure-virtual methods. Declaring the method pure virtual is documenting the idea that the base class will not provide the functionality, and is therefore requiring that all derived class must provide some code to support this concept.


    "A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class that is not abstract" - Wikipedia

    good reasons why to refactor the code?

    Readability.