#include <iostream>
using namespace std;
// Base class
class Shape {
protected:
int width;
int height;
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
};
// Derived class
class Rectangle : public Shape {
public:
int getArea() {
return (width * height);
}
};
int main() {
Rectangle rect;
rect.setWidth(5);
rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << rect.getArea() << endl;
return 0;
}
Here's an example of a class in C++ that demonstrates single inheritance:
cpp#include <iostream>
using namespace std;
// Base class
class Shape {
protected:
int width;
int height;
public:
void setWidth(int w){
width = w;
}
void setHeight(int h){
height = h;
}
};
// Derived class
class Rectangle : public Shape {
public:
int getArea(){
return (width * height);
}
};
int main(){
Rectangle rect;
rect.setWidth(5);
rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << rect.getArea() << endl;
return 0;
}
This program defines two classes, Shape and Rectangle. Shape is the base class and Rectangle is the derived class, which inherits from Shape using the public keyword.
The Shape class has two protected member variables, width and height, and two public member functions, setWidth() and setHeight(), to set the values of these variables.
The Rectangle class is a derived class that inherits the Shape class. It has a public member function getArea() that calculates and returns the area of the rectangle using the width and height member variables inherited from the Shape class.
In the main() function, a Rectangle object is created and its setWidth() and setHeight() member functions are used to set the width and height of the rectangle. Then, the getArea() member function is called on the Rectangle object to calculate and display the area of the rectangle.
The output will be:
Total area: 35
This demonstrates single inheritance, where the Rectangle class inherits the Shape class, which serves as the base class for the Rectangle class.