Why do we need inheritance in C++?
Inheritance allows us to reuse member values and functions from previously written classes to build new classes.
Give a simple example of objects in the real world that could be modelled in C++ using inheritance.
You could define a class called clothing, that contains a bunch of members. You may need to write individual clothing pieces by class (shirt, jacket, jeans, etc.) that will be able to inherit properties from the clothing class (size, colour, etc.).
What is a superclass and what is a subclass?
A superclass aka parent class or base class is the class that is being inherited from. A subclass is the class that is doing the inheriting from the superclass.
How would you write a public inheritance in C++?
Using my example above, I’d do it like this:
#include <iostream>
#include <string>
using namespace std;
class Clothing {
public:
string color;
bool clean;
Clothing() {
color = "not supplied";
clean = false;
}
Clothing(string _color, bool _clean) {
color = _color;
clean = _clean;
}
void printStatus () {
cout << "This item of clothing is "<<color<< endl;
if (clean == true) {
cout << "This item of clothing is clean" << endl;
}
else {
cout << "This item of clothing is dirty" << endl;
}
}
};
class Jeans : public Clothing {
public:
int length;
int waistSize;
Jeans(int _length, int _waistSize) {
length = _length;
waistSize = _waistSize;
}
void printFullStatus() {
printStatus();
cout << "This item has a waist size of "<<waistSize<< endl;
cout << "This item has a leg length of "<<length<< endl;
}
};
int main()
{
Jeans firstPair(73, 32);
firstPair.color = "Blue";
firstPair.clean = true;
firstPair.printFullStatus();
return 0;
}
.
In what ways can a subclass extend the functionality of a superclass?
It can provide different and versatile ways of changing members within the superclass by using member functions that have been defined in the subclass.