An important feature of object-oriented programming is "inheritance". It can use all the functions of existing classes and extend these functions without re-writing the original classes.
From the characteristics of "inheritance", one of the roles of inheritance is to make the derived classes use the methods of the base class without any difference to realize logic reuse.
However, from the perspective of virtual functions, especially pure virtual functions, "inheritance" plays a more role in "logical hierarchy" to achieve loose coupling between modules.
For example:
Class Logger
{
Public:
Virtual void log (char * info) = 0;
}
Void func (logger)
{
// Do something
Logger. Log ("func exit .");
}
For Class logger, there is a pure virtual function log (we define it as the function logic for logging). Another function func calls the LOG method when exiting, record function exit.
Why is it implemented like this?
In actual projects, the Code architecture is often divided into different modules/layers. For modules/systems developed based on the base, there may be different log formats.
According to the traditional idea, if logger-based systems have different requirements, then different log methods are not enough?
Such an idea is often disastrous. In extreme cases during actual operation, logger-type systems are often maintained in one team, while systems developed based on logger may be in another team or even another enterprise. According to the traditional idea, the "coupling" between the two teams is generated.
At this time, "inheritance" comes in handy. logger-based systems can completely rewrite their own log functions:
Class newlogger: Public Logger
{
Public:
Void log (char * info)
{
//...
}
}
When calling the func function, you only need to call the function as follows:
Newlogger;
Func (newlogger );
The concept of "hierarchy" is one of the most common ideas for solving problems in the computer system. Inheritance in OOP is produced by catering to this idea to a certain extent, similar to the "callback function" mechanism in C language. The dependency reversal principle in the solid design principle is supported by inheritance.