What is Inheritance? Explain it with an example.
Inheritance : - One of the most important features of OO design is code-reusability and it is achieved through inheritance. Inheritance is the process by which objects of one class acquire the properties of another class. By this we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have combined features of both the classes.
- This allows the programmer to reuse a class that is almost, but not exactly, what he wants and change it according to his needs.
Class Bird
{
bool has_feathers;
int legs;
public:
{
//Functions to manipulate data
}
};
Class FlyingBird : public Bird
{
int highestAltitude;
public:
{
//Functions to manipulate data
}
};
- Here, Class FlyingBird is derived from Class Bird. FlyingBird has all the attributes of Bird plus it has its own attribute highestAltitude which tells the highest altitude at which it can fly. Bird is called as base class and FlyingBird is called as derived class.