"Effective C + +" Reading Note 09: Never call the virtual function during construction and destructor

Source: Internet
Author: User
Tags constructor

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.

Related Article

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.