简体   繁体   中英

how can I use an inherited method and the same base class method?

let's say I have a class animal and a class dog that inherits animal. Let's say I want to call a method called 'eat()' that is specific to dog but there is some shared eat code between all animals, so I know I can make 'eat()' virtual but then it won't use the base class code, should I just call my base class 'eatAll()', for example, and then every eat method from a specific animal will have to call that? Just looking for the best design I guess. This is in c++

This is classic template method pattern . Basically:

class Animal
{
    void Eat() 
    {
       //stuff specific to all animals

       SpecificEat();
    }
    virtual void SpecificEat() = 0;
};

class Dog : Animal
{
    virtual void SpecificEat()
    {
        //stuff specific to dog
    }
};

Using this approach, you don't have to explicitly call the base class method in derived classes' overrides. It's called automatically by the non- virtual Eat() and the specific functionality is implemented by virtual SpecificEat() .

I would suggest that your base class interface have hooks to call into specific functionality of derived types. This is called the template method pattern. Here's an example:

class Animal
{
public:
   void eat()
   {
      std::cout << "Mmmm... It's ";
      do_eat();
   }

private:
   virtual void do_eat() = 0;
};

class Dog
   : public Animal
{
   virtual void do_eat()
   {
      std::cout << "Dog Food!\n";
   }
};

class Human
   : public Animal
{
   virtual void do_eat()
   {
      std::cout << "Pizza!\n";
   }
};

Just call the base class' method.

class Dog : public Animal
{
public :
  void Eat()
  {
    // .. MAGIC
    Animal::Eat();
  }
};

Note that if your Animal class's Eat method is pure virtual (which I doubt), this will not link.

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