First of all, for an inheritance system, the constructor is invoked from the base class, and the destructor is just the opposite, starting with the outermost class.
For a call to the virtual function in the constructor, give an example:
1 class Transaction //所有交易的基类
2 {
3 public:
4 Transaction();
5 virtual void logTransaction() const = 0;//日志记 录,因交易类型的不同而有不同的记录
6 }
7
8 Transaction::Transaction()//构造函数实现
9 {
10
11 logTransaction();//调用了日志记录
12 }
13
14 class Sell: public Transaction
15 {
16 public:
17 virtual void logTransaction() const;
18
19 }
The Sell class inherits from the base class if the execution:
1 Sell a; //派生类
The transaction constructor is executed first, and the transaction constructor invokes the transaction version of the Logtransaction function (remember that the virtual function in the base class constructor does not fall into the derived class).
As you all know, the logtransaction in the base class has not yet implemented code, which obviously creates a connection error.
As a workaround: Declare logtransaction as a non-virtual function, and then implement the method by which the derived class passes the arguments to the base class.
1 class Transaction
2 {
3 public:
4 Transaction (const std::string& logInfo);
5 void logTransaction(const std::string& logInfo) const;//改成非virtual实现
6
7 };
8
9 Transaction::Transaction(const std::string& logInfo)
10 {
11
12 logTransaction(logInfo);//同样在构造函数中调用
13 }
14
15 class Sell: public Transaction
16 {
17 public:
18 Sell()
19 :Transaction(createLog())//将log信息传给基类构造函 数
20 {
21
22 }
23 }
As a result, the derived class solves the problem by passing the construction information up to the base class constructor.