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.h
in LogStreamConsumer
defined 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 LogStreamConsumerBase
prior to std::ostream
:
class LogStreamConsumer : protected LogStreamConsumerBase, public std::ostream
, It will first call the LogStreamConsumerBase
constructor of:
LogStreamConsumerBase(severityOstream(severity), severityPrefix(severity), severity <= reportableSeverity)
The following are LogStreamConsumerBase
definitions of the constructor:
LogStreamConsumerBase(std::ostream& stream, const std::string& prefix, bool shouldLog)
: mBuffer(stream, prefix, shouldLog)
{
}
In this step initializes LogStreamConsumer
member variables mBuffer
.
In LogStreamConsumerBase
the constructor returns and then just call std::ostream
the constructor:
std::ostream(&mBuffer)
You can see this step requires mBuffer
the member variable, which is why the emphasis on code comments LogStreamConsumerBase
and std::ostream
the reasons for the order of succession can not be replaced.