Exercise 2: Displaying Message Using Virtual Functions

This exercise requires you to implement the concept of virtual functions to display information about two base classes.

We'll cover the following

Problem Statement

You will first build three classes:

  • Mammal (parent class)
  • Dog (derived class)
  • Cat (derived class)

Dog and Cat class will inherit from Mammal.

In the exercise you have to implement the following:

  • Mammal class:

    • Has one protected property, age, of the mammal.
    • A default constructor
    • A constructor that takes the age of mammal as input and sets it.
    • The method Eat() that displays “Mammal eats food”.
    • Method Speak() that displays “Mammal speaks mammalian!!”.
    • Method get_Age() which returns the age of the mammal.
  • Dog class:

    • Inherits all the members from Mammal class.
    • It’s constructor calls on the Mammal class constructor with parameters.
    • Implement all member functions of Mammal class for Dog class.
    • Eat() should display “Dog eats meat”.
    • Speak() should display “Dog barks: ruff! ruff!”.
    • get_Age() should return Dog’s age.
  • Cat class:

    • Inherits all the members from Mammal class.
    • It’s constructor calls on the Mammal class constructor with parameters.
    • Implement all methods of Mammal class for Cat class.
    • Eat() should display “Cat eats meat”.
    • Speak() should display “Cat meows: Meow! Meow!”.
    • get_Age() should return Cat’s age.

Hint: Think along the direction of virtual methods and their use to implement the same method for different classes separately.

Here’s a sample result which you should get.

Input:

Dog(5);
Cat(4);

Expected Output:

Get hands-on with 1400+ tech skills courses.