What is the advantage of creating methods in an interface, but is protected in the implementation?

In my C ++ application, I have an interface that looks like this:

class ICalculator
   {
   public:
      virtual double calculateValue(double d) = 0;
   };

I have implementations of this interface that look like this:

class MySpecificCalculator
   {
   public:
      virtual double calculateValue(double d);
   };

Now my colleague complains about this and tells me that it is better to have a calculateValue method. In this way, we can guarantee that callers always go through the interface and not through a direct implementation.

Is this the right observation? Is it really better to make the interface implementation secure? Or can't we make it private then?

+3
source share
2 answers

Your colleague is right.

Never publish virtual functions.

№ 1: , .

№ 2: .

№ 3: , .

:

№ 4: , , .

+10

, :

class ICalculator
{
public:
    virtual double calculateValue(double d) const = 0;
};

class MySpecificCalculator : public ICalculator
{
protected:
    double calculateValue(double d) const;
};

void Calc(double d, const ICalculator& c)
{
    std::cout << "Result = " << c.calculateValue(d) << std::endl;
}

int main ()
{
    MySpecificCalculator c;
    c.calculateValue(2.1);  // dont do this
    Calc(2.1, c);  // do this instead
    return 0;
}

. . calculateValue , . MySpecificCalculator , .

Btw NVI, Chubsdad ( "" ).

0

Source: https://habr.com/ru/post/1774037/


All Articles