构造函数(析构函数)中调用虚函数

来源:百度知道 编辑:UC知道 时间:2024/09/27 12:25:10
构造函数(析构函数)中调用虚函数的例子??
调用结果是什么?
为什么?
谢谢~

根据Effective C++ (3rd Edition) ---- Item 9:
Never call virtual functions during construction or destruction.
(不要在构造函数和析构函数中调用虚函数)
其中举例为:(英文)
class Transaction {
public:
Transaction();
virtual void LogTransaction() const = 0;
// ...
};

Transaction::Transaction()
{
// ...
LogTransaction();
}

class BuyTransaction : public Transaction {
public:
virtual void LogTransaction() const;
// ...
};
Consider what happen when this code is executed:
BuyTransaction b;
Clearly a BuyTransaction constructor will be called, but firt, a Transaction constructor must be called; base class parts of derived class objects are constructed before derived class parts are. The last line of the Transaction constructor calls the virtual function longTransaction, but this is where the surprise comes in. The version of logTransaction that't called is the one in Transaction, not the one