-4

Let's say I've a class fruit and several class like apple,mango etc,Now i want to create a single function that would accept fruit and it's all derived classes object's as argument,How can i do so?

I have not tried anything yet!

  • 1
    Make the parameter a pointer or reference to base class. Search for *"dynamic binding"* in your favorite [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Oct 29 '22 at 08:39
  • 1
    `void eat(Fruit const& fruit){ ... }` (or remove the `const`, if you need to modify the fruit). – fabian Oct 29 '22 at 08:45

1 Answers1

0

You can make the function parameter to be a reference or a pointer to the base class as shown below.

void eat(const Fruit* f)
{
    //code here
}

Or

void eat(const Fruit& f)
{
   //code here
}

You can remove the low-level const if you want to be able to make changes through f.

Jason
  • 36,170
  • 5
  • 26
  • 60