Skip to content

Commit 180ae1f

Browse files
author
Michael McLeod
committed
avoid multiple inheritance
1 parent 9ad8a56 commit 180ae1f

1 file changed

Lines changed: 1 addition & 1 deletion

File tree

05libraries/sec01DesigningClasses.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ std::unique_ptr<AbstractDataManager> DataManagerFactory(std::vector &v)
446446

447447
When working with interfaces which define minimal behaviour, it is possible that useful objects will need to implement more than one set of behaviour. This is easy to do when the sets of behaviour are nested i.e. we can model it with a chain of inheritance. (An `Undergraduate` is a type of `Student` which is a type of `UniversityMember`.) Things can be slightly more complicated when an object implements two different functionalities which are independent of one another, for example a `StudentTeachingAssistant` is a `Student` and an `Employee`, but a `Student` is not a type of `Employee` (and vice versa).
448448

449-
In this case we would need to implement two interfaces independently, which can be done using multiple inheritance. Multiple inheritance is a complex topic in C++ that goes beyond implementing multiple abstract interfaces, so you should think carefully about whether, and how, you use it.
449+
In this case we would need to implement two interfaces independently, which can be done using multiple inheritance. Multiple inheritance is a complex topic in C++ that goes beyond implementing multiple abstract interfaces, so you should think carefully about whether, and how, you use it. A good rule of thumb is to avoid it where you can (and limit inheritance to tree-like structures), and if you _do_ need to use it then limit yourself to inheritance from abstract classes with no explicit implementation or data members.
450450

451451
As an example, let's say we have a computer system that models people in a university and it has two classes `Student` and `Employee` to represent roles which can be taken by people in the university. We'll have some systems that process employees, and some that deal with students. There will likely be multiple types of students and employees, which we can fit seamlessly into these systems by having derived classes which inherit from `Student` or `Employee`. Now say we want a class to model a student teaching assistant - these are both students _and_ employees, and should be able to function in parts of the system that deal with either. In this case we need a class that is recognisable as both a `Student` and an `Employee` in our program. We can do this by declaring multiple inheritance:
452452
```cpp

0 commit comments

Comments
 (0)