1. Why do we need inheritance in C++?
Inheritance allows us to build upon what has already been established. You can add more specifics while using the same functionality.
2. Give a simple example of objects in the real world that could be modeled in C++ using inheritance.
Shape > Triangle > Right Triangle
Part 2:
1. What is a superclass and what is a subclass?
The superclass would be the parent and the subclass would be the child. The child inherits attributes from the parent.
2. How would you write a public inheritance in C++?
#include
#include
class Person
{
public:
std::string m_name;
int m_age;
std::string getName() const { return m_name; }
int getAge() const { return m_age; }
Person(std::string name = "", int age = 0)
: m_name(name), m_age(age)
{
}
};
// Employee publicly inherits from Person
class Employee: public Person
{
public:
double m_hourlySalary;
long m_employeeID;
Employee(double hourlySalary = 0.0, long employeeID = 0)
: m_hourlySalary(hourlySalary), m_employeeID(employeeID)
{
}
void printNameAndSalary() const
{
std::cout << m_name << ": " << m_hourlySalary << '\n';
}
};
int main()
{
Employee James(20.25, 12345);
James.m_name = âJamesâ; // we can do this because m_name is public
James.printNameAndSalary();
return 0;
}
This Prints: James 20.25
3. In what ways can a subclass extend the functionality of a superclass?
The subclass can add more detailed and specific information.