In object-oriented programming, inheritance allows us to create new classes that inherit the properties and behaviors of existing classes. This feature enables us to extend functionality, modify existing behavior, or encapsulate new features without altering the original code.
Base Class Definition
Let's start with a basic base class named Base
:
#include <iostream>
class Base {
protected:
int m_value;
public:
Base(int value) : m_value(value) {}
void identify() const {
std::cout << "I am a Base\n";
}
};
Here, Base
has a protected member m_value
and a member function identify()
.
Derived Class Inheritance
Next, we create a derived class called Derived
that inherits from the Base
class. The derived class introduces its own constructor and a new member function, getValue()
:
class Derived : public Base {
public:
Derived(int value) : Base(value) {}
int getValue() const {
return m_value;
}
};
In this example, Derived
extends the functionality of Base
without modifying its directly.
Adding New Functionality
The key concept here is adding new functionality to the derived class. For instance, we have introduced a method getValue()
in Derived
to retrieve the value of m_value
.
int getValue() const {
return m_value;
}
Usage of Derived Class
Now, let's see how we can utilize the derived class:
int main() {
Derived derived{5};
std::cout << "derived has value " << derived.getValue() << '\n';
return 0;
}
In this example, we create an object of type Derived
, initialize it with a value of 5, and then use the getValue()
method to retrieve and print the value.