Analysis of C ++ multi-inheritance and c
Inheritance is one of the three main characteristics of object-oriented. However, different object-oriented languages have their own views on the implementation and usage of inheritance. Some languages support multiple inheritance, while some languages only support single inheritance.
Multi-inheritance indeed introduces greater complexity. Therefore, when you have to use it, you must pay attention to several processing methods to make the code more efficient and understandable.
- Encapsulate functions with the same name
For functions with the same name in multiple parent classes, the best solution is to add a new helper class for these parent classes. In the helper class, use different function names to encapsulate functions with the same name. This makes it easier to call these functions with the same name.
Class CSofa {public: // function of the same name virtual void Clean () ;}; class CBed {public: // function of the same name virtual void Clean () ;}; // auxiliary class AuxSofa: public CSofa {public: virtual void CleanSofa () = 0; // transfer to the new interface virtual void Clean () {CleanSofa () ;}}; // auxiliary class AuxBed: public CBed {public: virtual void CleanBed () = 0; // transfer to the new interface virtual void Clean () {CleanBed () ;}}; class CSofaBed: public AuxSofa, public AuxBed {public: // clear interface name, avoiding virtual void CleanBed (); virtual void CleanSofa ();};
- Use virtual inheritance to conquer diamond inheritance
Class D often holds two copies of Class A data, resulting in A huge waste of space. You can use virtual inheritance to avoid the appearance of multiple A-class contents.
class CSofa{public:virtual void Clean();};class CBed{public:virtual void Clean();};class CSofaBed : public virtual CSofa, public virtual CBed{public:};