OOP 5 - Inheritance (cpp)
OOP 5 - Inheritance (cpp)
INHERITANCE
Purpose:
o Reusability: Allows derived classes to reuse code from the base class, avoiding
redundancy.
o Extensibility: Derived classes can extend or modify the functionality of the
base class.
o Maintainability: Changes made to the base class can propagate to derived
classes, making the system easier to maintain.
Derived Class: A class that inherits from another class (the base class). It can access the
base class's public and protected members, and can also add new members or override base
class methods.
SIMPLE INHERITANCE
CONSTRUCTOR INHERITANCE
NOTE: The constructor of the Base class is called first because Derived inherits from Base.
These prints:
"Base class constructor"
"Derived class constructor"
Q1: Create a base class called Animal with a member variables name (string) and age (int).
Create a derived class called Dog that inherits from Animal with a member variables color
(string) and getters (Get value Functions) for all these three variables. In the main function,
create an object of Dog and call these functions.
Q2: Create a base class called Book with member variables title (string), author (string), and
isbn (string). Create two derived classes, Fiction and NonFiction, which add additional
member variables (genre for Fiction and subject for NonFiction). Implement getter functions
in all classes to retrieve the values of the variables. In the main function, create objects of
Fiction and NonFiction, and print their details.
Q3: Create a base class Student with member variables name (string) and age (int). Create a
derived class GraduatedStudent that inherits from Student and adds a member variable
degree (string). Implement setter functions to set the values of all the variables. In the main
function, create an object of GraduatedStudent, set its values using setter functions, and print
its details.