Hands-On Exercises: Building Inheritance-Based Programs
C++ supports inheritance, which allows you to create a new class based on an existing class, inheriting its member variables and member functions. This allows you to reuse code and create a hierarchy of related classes.
Here is an example of an inheritance-based program in C++:
#include <iostream>
class Shape {
public:
double width, height;
void setWidth(double w) {
width = w;
}
void setHeight(double h) {
height = h;
}
};
class Rectangle : public Shape {
public:
double area() {
return width * height;
}
};
int main() {
Rectangle rect;
rect.setWidth(5);
rect.setHeight(10);
std::cout << "Rectangle area: " << rect.area() << std::endl;
return 0;
}
In this example, a class called "Shape" is defined with member variables "width" and "height", and member functions "setWidth()" and "setHeight()".
The next class, "Rectangle", is defined with the keyword "class", followed by the name "Rectangle" and the keyword ": public Shape". This means that the class "Rectangle" is inheriting from the class "Shape", and it has access to the member variables and member functions of the class "Shape".
In the class "Rectangle", a member function called "area()" is defined which calculates and returns the area of a rectangle by multiplying the width and height.
In the main function, an object of the class "Rectangle" is created with the line "Rectangle rect;". This object has access to the member variables and member functions of both the class "Rectangle" and the class "Shape".
The next two lines, "rect.setWidth(5);" and "rect.setHeight(10);", call the member functions "setWidth()" and "setHeight()" to set the values of the width and height of the rectangle.
The next line, "std::cout << "Rectangle area: " << rect.area() << std::endl;", calls the member function "area()" of the object "rect" and prints the result to the console, followed by a new line.
Finally, the line "return 0;" is used to exit the main function and the program, indicating that it has completed successfully.
This is just a basic example of how inheritance can be used in C++. The language offers many more features such as polymorphism, virtual functions, and abstract classes which enables the developer to write complex and powerful software using object-oriented programming paradigm.