A way to ensure the use of an interface in C ++

In C ++, suppose I have a Derived class that implements the BaseInterface interface class , where BaseInterface has only pure virtual functions and a virtual destructor:

class BaseInterface
{
  public:
    virtual void doSomething() = 0;
    ~BaseInterface(){}
};

class Derived : public BaseInterface
{
  public:
    Derived() {}
    ~Derived(){}

  protected:
    virtual void doSomething();

  private:
    int x;
};

No classes outside the Derived class hierarchy should access Derived :: doSomething () directly, that is, it should only be accessed polymorphically through the BaseInterface class. To enforce this rule, I made Derived :: doSomething () protected. This works well, but I'm looking for pro / con opinions on this approach.

Thank!

Ken

+3
source share
5 answers

, (NVI): public, virtual:

class BaseInterface
{
  public:
    virtual ~BaseInterface(){}
    void doSomething() { doSomethingImpl(); }

protected:
    virtual void doSomethingImpl() = 0;
};

class Derived : public BaseInterface
{
  public:
    Derived() {}
    virtual ~Derived(){}

  protected:
    virtual void doSomethingImpl();

  private:
    int x;
};
+8

, , ? , , : static_cast<BaseInterface&>(o).doSomething() - o.doSomething(). ... , , - ?

, ( , ) . , , ( ), .

+3

, , ISO/IEC 14882: 2003 (E) 11.6.1 , . , - . , AFAIK.

( 11) , .

[Example:

   class B 
   { 
     public:
     virtual int f();
   };

   class D : public B 
   { 
     private:
     int f();
   };

   void f() 
   {
     D d; 
     B* pb = &d; 
     D* pd = &d;

     pb->f(); // OK: B::f() is public, 
              // D::f() is invoked

     pd->f(); // error: D::f() is private
   }

—end example]

, , - (B * ). - , (D ), .

+2

- . BaseInterface * , doSomething(). , .

+1

. , doSomething(), , . :

class BaseInterface
{
  public:
    virtual void doSomething() = 0;
    ~BaseInterface(){}
};

class Derived : public BaseInterface
{
  public:
    Derived() {}
    ~Derived(){}

      virtual void doSomething(){}

  private:
    int x;
};

class SecondDerived : public Derived
{
  public:
    SecondDerived() {}
    ~SecondDerived(){}

  private:
    int x;
};

int main(int argc, char* argv[])
{
    SecondDerived derived;
    derived.doSomething(); //Derived::doSomething is called

    BaseInterface* pInt = &derived;
    pInt->doSomething(); //Derived::doSomething is called

    return 0;
}
0
source

All Articles