About C ++ private inheritance and c private inheritance

Source: Internet
Author: User

About C ++ private inheritance and c private inheritance

Many C ++ programmers have never used private inheritance to design their classes. Indeed, if private inheritance is used but public inheritance is used, the implementation of program functions is not affected. However, this misuse is a misaligned description, which may lead to misunderstandings of readers and even the loss of class users. When writing a class declaration, we are actually designing an intent. What designers need is precise description.

  • Private inherited string outsourcers

To explain private inheritance, Let's first look at co-occurrence inheritance to make a comparison.

Public inheritance is essentiallyIs-. For example, to describe a type of car, you can perform the following design:

class Car{};class Jeep : public Car{}

Private inheritance, subclass can only be in ClassUse the features of the parent class, instead of opening the features of the parent class to the outside in the form of interfaces, that is, Subclass objectYou cannot directly use the functional interfaces of the parent class. Therefore, the meaning of private inheritance becomes: Sub-classes can use the features of the parent class to implement their own functions.. This is typical Has-.

class Engine{public:    void Run();};class Car : private Engine{public:    void Drive()    {        // let engine go!        Run();    }};
The link description is equivalent to a combination, for example:

class Car{    ...private:    Engine m_engine;}

  • Private inheritance VS combination

Private inheritance brings too much program overhead, but the combination is short and fast. Therefore, when designers want to describe the relationship between Has-,Combination is preferred.

However, you must use private inheritance in either of the following ways:




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.