Concepts Related To Inheritance

Concepts Related To Inheritance

OOPs series in C++

·

2 min read

Recap Of Inheritance:

  • Derived class inherit all characteristics from the base class
  • Besides inherited characteristics derived class has its unique characteristics

    Dive Deep Into Inheritance:

    Here are some common terminologies associated with inheritance.

  • Generalization

  • Sub-Typing
  • Specialization

Generalization:

Suppose there are three classes. Student, Teacher, and Doctor. Each of these have some common attributes(name, gender, age) and methods(eat( ), walk( )). So, if we extract all these common characteristics into a new class and then inherit original classes from this new class. This concept is called Generalization.

Example:

new1.png

We can use the concept of generalization here:

new2.png

Sub-Typing:

If base class and derived class are behaviorally compatible. Behavioral compatible means that the derived class can replace the base class. Sub-Typing can also be referred to as an extension of the default behavior of the base class.

subtype.png

Specialization:

If the base class and derived class are not behaviorally compatible, so derived class cannot replace the base class. This is called specialization.

Example:

Suppose, we have a base class “Person”. It has attribute “age(1-100)” and a method “set_age( )”. Now, we derived an “Adult” class, but this has some restriction in the “set_age( ) function”- that restriction is, this function will only work if the user age is 18-100. Means derived class derived a method from parent class but is using by its way. As these are not behaviourally compatible, here is a specialized case.

speci.png

Over-riding:

Sometimes a class needs to override the default behavior of the base class means the derived class used the base class operations in its way.

It provides us some benefits:

  • Provide behavior specific to derived class
  • Improve functionality
  • Restrict default behavior
  • Extend default behavior

Specific Behaviour:

In this example, the Circle class derived the” draw” method from the base class “Shape” but the Circle class use this method in a different way, just like the Line class and Triangle class.

specific.png

Restrict The Default Behaviour:

restrict.png

Extend The Behaviour:

extend.png

Improve Functionality:

improve.png

Conclusion :

There are some concepts related to inheritance like generalization, sub-typing, and specialization. All of these can be achieved by over-riding. In this blog, we took a glimpse of what inheritance is. In upcoming blogs, we will look at types of associations between classes and between objects.

Happy Learning :)