In part 1, C++ Inheritance – 1 – Base and Derived classes, I introduced you to inheritance and demonstrated it with an example. We had the base class Shape and the derived classes Rectangle and Triangle. The base class had public methods for setters and getters and two private members width and height. Here’s what it looked like:
#include <iostream>
// Base class
class Shape {
public:
void setWidth(int width) {
this->width = width;
}
void setHeight(int height) {
this->height = height;
}
double getWidth() {
return width;
}
double getHeight() {
return height;
}
private:
double width;
double height;
};
// Derived class
class Rectangle : public Shape {
public:
double getArea() {
return getWidth() * getHeight();
}
};
// Another derived class
class Triangle : public Shape {
public:
double getArea() {
return (getWidth() * getHeight()) / 2;
}
};
A derived class cannot access a base class’s private members. If we want to use a base class’s private members in a derived class we need to create public setters and getters for those members in the base class. However, there is another way to program this. Instead of making width and height private in Shape, we can make them protected. By using the access specifier protected, width and height can be accessed within the base class itself and by any class derived from the base class. Now we can access the members width and height directly from Rectangle and Triangle simply by the members name, and we don’t need to use getWidth() or getHeight() to calculate the area anymore, as shown in the code below. Compare the methods getArea() in Rectangle and Triangle in the code below and above.
#include <iostream>
// Base class
class Shape {
public:
void setWidth(int width) {
this->width = width;
}
void setHeight(int height) {
this->height = height;
}
double getWidth() {
return width;
}
double getHeight() {
return height;
}
protected:
double width;
double height;
};
// Derived class
class Rectangle : public Shape {
public:
double getArea() {
return width * height;
}
};
// Another derived class
class Triangle : public Shape {
public:
double getArea() {
return (width * height) / 2;
}
};
Both of the above implementations will produce the same output from the code below.
int main() {
Rectangle rect;
rect.setWidth(5);
rect.setHeight(5);
Triangle tri;
tri.setWidth(10);
tri.setHeight(10);
std::cout << "The rectangle's area is " << rect.getArea() << "\n";
std::cout << "The triangle's area is " << tri.getArea() << "\n";
}
Output:
The rectangle's area is 25
The triangle's area is 50
Author
2020-12-16
This article goes through how to overload relational operators in C++. Create your own user-defined types and use overloaded operators with them.
Inheritance is a form of software reuse in which a class can use another class’s methods and members and modify them.
When a derived-class object is instantiated, a chain of constructor calls begins. Similarly, when a derived-class object is destroyed, destructor calls begins