Private method in C ++ interface?

Why do I want to define a C ++ interface containing private methods?

Even in the case when methods in the public domain will technically assume to act like template methods that use private methods to implement the interface, even so, we are talking about technical characteristics. straight from the interface.

Is this not a deviation from the initial use of the interface, i.e. public contract between external and internal?

You can also define a friends class that will use some private methods from our class and, thus, implement the implementation through the interface. This may be an argument.

What other arguments for defining private methods in a C ++ interface?

+5
source share
4

OO , , , , , . NVI, , - , , :

  • ,

++ ( ), , - - - .

: , , , . . , , , 'private'. 'private' , .

, , NVI, , :

class Base {
public:
   void foo() { 
      foo_impl();
   }
private:
   virtual void foo_impl() = 0;
};

foo() { foo_impl(); } , , , , . , , , , : ( foo_impl)

void Base::foo() {
   scoped_log log( "calling foo" ); // we can add traces
   lock l(mutex);                   // thread safety
   foo_impl();
}

, , .

+6

, . :

class CharacterDrawer {
public:
   virtual ~CharacterDrawer() = 0;

   // draws the character after calling getPosition(), getAnimation(), etc.
   void  draw(GraphicsContext&);

   // other methods
   void  setLightPosition(const Vector&);

   enum Animation {
      ...
   };

private:
   virtual Vector getPosition() = 0;
   virtual Quaternion getRotation() = 0;
   virtual Animation getAnimation() = 0;
   virtual float getAnimationPercent() = 0;
};

, , , ..

"setPosition", "setAnimation" .. , "" , "" .

, , .

+3

++ , ?

/: () , , public . , .

, (, , ).

( ) , . , .

(.. , ). , , COM/DCOM/XPCOM ( ). , .

+3

In the implementation of the template method, it can be used to add a specialization restriction: you cannot call a virtual method of a base class from a derived class (otherwise the method will be declared as protected in the base class)

class Base
{
private:
   virtual void V() { /*some logic here, not accessible directly from Derived*/}
};

class Derived: public Base
{
private:
   virtual void V() 
   { 
      Base::V(); // Not allowed: Base::V is not visible from Derived
   }
};
0
source

All Articles