Welcome to the exciting world of C++ public inheritance! Today, we're going to learn how to use this powerful feature to create efficient and reusable code. Let's dive in!
Public inheritance is a type of inheritance in C++ where one class (the derived or child class) inherits properties and methods from another class (the base or parent class). This relationship is established using the : operator and the public keyword.
First, let's create a base class. This class will define the properties and methods that the derived class will inherit.
// Base Class
class Shape {
public:
std::string color;
double area;
void setColor(std::string c) {
color = c;
}
};Now, let's create a derived class that inherits from the Shape class. We'll name it Rectangle.
// Derived Class
class Rectangle : public Shape {
private:
double width, height;
public:
// Constructor
Rectangle(double w, double h, std::string c) {
width = w;
height = h;
setColor(c);
}
// Calculate and set the area
void setArea() {
area = width * height;
}
};In the above code, we've created a Rectangle class that inherits from the Shape class. The Rectangle class has its own width and height variables, and it also inherits the color and setColor methods from the Shape class.
Now that we have our derived class, let's use it in a simple program.
#include <iostream>
int main() {
Rectangle rect(5, 4, "Red");
rect.setArea();
std::cout << "The area of the rectangle is: " << rect.area << std::endl;
std::cout << "The color of the rectangle is: " << rect.color << std::endl;
return 0;
}In the main function, we create a Rectangle object, calculate its area, and print both the area and the color.
Question: What is the purpose of the : operator in C++ when creating a derived class?
A: To define the base class
B: To define the public keyword
C: To define the constructor
Correct: A
Explanation: The : operator is used to define the base class in a derived class.
That's all for today! We've learned about public inheritance in C++, created a derived class, and used it in a simple program. In the next lesson, we'll explore more advanced topics related to C++ inheritance. Keep coding! š