Analysis of C ++ multi-inheritance and c

Source: Internet
Author: User

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:};






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.