Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create a new class (called the derived class) from an existing class (called the base class). The derived class inherits the properties and behaviors of the base class, and can also add its own unique properties and behaviors.
In C++, inheritance is defined using the :
symbol followed by the access specifier (public
, protected
, or private
) and the name of the base class.
1// Base class
2
3class Shape {
4public:
5 // Base class members
6};
7
8// Derived class
9
10class Rectangle : public Shape {
11public:
12 // Derived class members
13};
In the example above, Rectangle
is the derived class and Shape
is the base class.
By using the public
access specifier, the derived class inherits the public members of the base class. In other words, the derived class can access and use the public members of the base class.
When an object of the derived class is created, it contains all the data members and member functions of the base class as well.
You can also override the base class member functions in the derived class to provide a different implementation. This is known as function overriding.
In the example below, the display()
member function is overridden in the Rectangle
class to provide a different implementation.
1// Base class
2
3class Shape {
4public:
5 void display() {
6 cout << "This is a shape" << endl;
7 }
8};
9
10// Derived class
11
12class Rectangle : public Shape {
13public:
14 void display() {
15 cout << "This is a rectangle" << endl;
16 }
17};
To create objects of the derived class, you can use the same syntax as creating objects of the base class.
1Shape* shape = new Shape();
2shape->display();
3
4Rectangle* rectangle = new Rectangle();
5rectangle->display();
When the display()
function is called on the shape
object, it will output "This is a shape". When the display()
function is called on the rectangle
object, it will output "This is a rectangle".
Inheritance allows for code reusability and helps in organizing and structuring the code in a logical manner. It is particularly useful in scenarios where you have common properties and behaviors shared among multiple classes, as it avoids code duplication and promotes a modular approach.
xxxxxxxxxx
}
using namespace std;
// Base class
class Shape {
public:
void display() {
cout << "This is a shape" << endl;
}
};
// Derived class
class Rectangle : public Shape {
public:
void display() {
cout << "This is a rectangle" << endl;
}
};
int main() {
Shape* shape = new Shape();
shape->display();
Rectangle* rectangle = new Rectangle();
rectangle->display();
return 0;