Exercise 4: 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
variable for age of the mammal. - A constructor that takes the age of mammal as input and sets it.
- The function
Eat()
that displays “Mammal eats food”. - Function
Speak()
that displays “Mammal speaks mammalian!!”. - Function
get_Age()
which returns the age of the mammal.
- Has one
-
Dog
class:- Inherits all the members from
Mammal
class. - Implement all
member
functions ofMammal
class forDog
class. Eat()
should display “Dog eats meat”.Speak()
should display “Dog barks: ruff! ruff!”.get_Age()
should return Dog’s age.
- Inherits all the members from
-
Cat
class:- Inherits all the members from
Mammal
class. - Implement all member functions of
Mammal
class forCat
class. Eat()
should display “Cat eats meat”.Speak()
should display “Cat meows: Meow! Meow!”.get_Age()
should return Cat’s age.
- Inherits all the members from
Hint: Think along the direction of
virtual
functions and their use to implement the same function for different classes separately.
Here’s a sample result which you should get.
Input:
Dog d(5);
Cat c(4);
Expected Output:
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy