How do I inherit multiple classes in a C object?

I have classA and ClassA inheriting ClassX and accessor methods of classX. How can I access the ClassY method with inheritance because multiple inheritance is not possible. I don't want to create another composition class for this. I want to use the same classA for multiple inheritance.

+3


source to share


3 answers


There is no multiple inheritance. The only way to achieve this is by merging the two-level hierarchy. Or, if ClassX inherits ClassY or ClassY, inherits ClassX (then ClassA inherits a child class X or Y).



If two classes do not match the design in the same hierarchy, then you may need to rethink your design and the reasons why you do not want to use composition.

+4


source


Like Objective-C, Swift does not have multiple inheritance. Swift uses protocols and categories to give you the same ability. You can define a protocol that defines a set of methods, and then add support for that protocol to multiple methods. You can often create protocol support in a category and then that category as needed.



+1


source


As said earlier, multiple inheritance is not supported by the language (neither ObjC nor Swift). If you need to inherit methods / properties from multiple classes, you will need to use composition. Alternatively, what the language allows you to do is enforce a class to conform to multiple protocols, which may or may not be a solution to the problem you are trying to solve.

I have come across very few cases where I thought I really needed to have multiple inheritance, and even for those cases, they were usually solved using the appropriate code design pattern (thinking of something like the Gang of Four design patterns). Basically, you want to abstract your code in such a way that multiple inheritance is no longer required.

0


source







All Articles