Inheritance refers to a class’s ability to derive properties and characteristics from another class. One of the most important aspects of Object-Oriented Programming is inheritance. This also allows:
In inheritance, there are two kinds of classes:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
When defining a derived class in this manner, the base class must already be defined or declared before the subclass declaration.
The Access Mode specifies how the properties of the base class will be inherited by the derived class, whether they are public, private, or protected.
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
Here the Shape class is the base class and its derived class is Rectangle.
Total area: 35
The availability of Superclass members in the subclass varies depending on the Access modifier used during inheritance. It can be private, protected, or open to the public as shown in the given table:
Base class member access specifier | Type of Inheritance | ||
---|---|---|---|
Public | Protected | Private | |
Public | Public | Protected | Private |
Protected | Protected | Protected | Private |
Private | Not accessible(Hidden) | Not accessible(Hidden) | Not accessible(Hidden) |
Note: also read about Class Members Pointers in C++
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…
A Binary Search Tree (BST) is a type of binary tree that satisfies the following…