C ++ multiple inheritance order

C ++ multiple inheritance order

Multiple inheritance order

When a class inherits from a plurality of categories, a plurality of its parent class constructor call will be in accordance with the order of succession.

The following are TensorRT/samples/common/logging.hin LogStreamConsumerdefined categories:

class LogStreamConsumer : protected LogStreamConsumerBase, public std::ostream
{
public:
    //! \brief Creates a LogStreamConsumer which logs messages with level severity.
    //!  Reportable severity determines if the messages are severe enough to be logged.
    //此處initializer list的順序:先LogStreamConsumerBase後std::ostream
    LogStreamConsumer(Severity reportableSeverity, Severity severity)
        //LogStreamConsumerBase(stream, prefix, shouldLog)
        : LogStreamConsumerBase(severityOstream(severity), severityPrefix(severity), severity <= reportableSeverity)
        //mBuffer繼承自LogStreamConsumerBase
        //注意這裡是先呼叫LogStreamConsumerBase建構子,
        //使得mBuffer指向一個有效的位置後,
        //才使用mBuffer來初始化ostream
        , std::ostream(&mBuffer) // links the stream buffer with the stream
        , mShouldLog(severity <= reportableSeverity)
        , mSeverity(severity)
    {
    }
    //...
}

Since the order of succession LogStreamConsumerBaseprior to std::ostream:

class LogStreamConsumer : protected LogStreamConsumerBase, public std::ostream

, It will first call the LogStreamConsumerBaseconstructor of:

LogStreamConsumerBase(severityOstream(severity), severityPrefix(severity), severity <= reportableSeverity)

The following are LogStreamConsumerBasedefinitions of the constructor:

LogStreamConsumerBase(std::ostream& stream, const std::string& prefix, bool shouldLog)
        : mBuffer(stream, prefix, shouldLog)
{
}

In this step initializes LogStreamConsumermember variables mBuffer.

In LogStreamConsumerBasethe constructor returns and then just call std::ostreamthe constructor:

std::ostream(&mBuffer)

You can see this step requires mBufferthe member variable, which is why the emphasis on code comments LogStreamConsumerBaseand std::ostreamthe reasons for the order of succession can not be replaced.

Reference Links

C++ multiple inheritance order

Published 90 original articles · won praise 9 · views 50000 +

Guess you like

Origin blog.csdn.net/keineahnung2345/article/details/104074980