More methods in derived classes than base class

坚强是说给别人听的谎言 提交于 2019-12-08 06:19:23

问题


I would like to ask a question about programming style in this case of derived class:

class A
{
public:
   virtual foo1()=0;
}

class B: public A
{
 public:
  virtual foo1();
  virtual foo2();
 }

class C: public A
{
 public:
  virtual foo1();
 }

int main() {
 B mB();
 C mC();
 mB.foo2() //OK!
 mC.foo2() // obviously, it is not correct
return 0;}

Therefore, should a derived class have less or equal public methods than the abstract base class?

If the derived classes require more methods, should these be private?


回答1:


There is nothing wrong with this class structure. There is nothing wrong with a derived class having more methods than the parent class-- it's quite commonplace. The line mC.foo2(); is just wrong, and that is not the fault of the classes.




回答2:


Derived classes will almost always have more public functions than base classes. This is the point of inheritance: you can define an abstract base class which only outlines the basic behavior of a variable, then derived classes can expand upon this basic behavior for specific cases.

An inherited class is always a specialization of the base class. It implements more specific functions (and usually more functions all together). In you're example, you're expecting two different specializations to behave the same way outside of the behavior defined by the base class. (foo2 is not defined in A). That's where the problem lies. If you need to define common behavior outside of A, the solution would be to create an intermediate class.

class Intermediate : public A
{
public:
    virtual foo1()=0;
    virtual foo2()=0;
}

class B: public Intermediate
{
public:
    virtual foo1();
    virtual foo2();
}

Now any class which can implement foo2 should extend Intermediate, and any function which requires functionality foo2 should ask for a variable with at least type Intermediate.




回答3:


A derived class must at least implement ALL abstract methods from the base class. This is the minimum. If you do add other methods, members or whatever is up to you.
But it would be not very smart to derive from the class and add nothing, because this is not what inheritance is for (at least IS-A-relationships). If you go for private inheritance it might be different.




回答4:


In nearly ALL projects I've worked on, we have had baseclasses that have less functionality than the derived class - in extreme cases, the baseclass may even just have nearly no functionality, but the derived class has dozens of functions and a half a dozen member variables.

This is exactly what derived classes are meant to do.

Obviously, you need to KNOW what kind of derived class you have, and only use the derived classes "extra" functions when they are available.



来源:https://stackoverflow.com/questions/15387581/more-methods-in-derived-classes-than-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!