简体   繁体   中英

Implementing an interface through a subset of its methods

I have a C++ interface with two methods. Any class implementing this interface need to implement at least one of the two methods but may define both. It is however not necessary to define both. What is the best pattern to use in such situation ?

Something like following:

class MyInterface
{
public:
  virtual ~MyInterface() {}

  virtual void foo() = 0;
  virtual void bar() = 0;
};


class MyAbstractClass :  public MyInterface
{
public:
  virtual ~MyAbstractClass();

  // Provide implementation for foo or bar
  virtual void foo() override { }
  virtual void bar() override { }
};

class MyNewClass : public MyAbstractClass
{
   // Implement either of foo or bar or can be both
};

IMHO the question is already wrong and also the class it is based on.

Case A: A class has a definition for a given method. The base implementation should provide an expectable behavior. In this case you are free to override it or not.

Case B: The method is abstract so you have to overwrite it in an expectable manner, otherwise the compiler won't compile.

There is no way to declare a "please overwrite one or both" in C++. A class given, which expect that, is (very) bad design.

So the question does not exist. If it exists, it is not possible to answer it with more details, as it depends on the context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM