posts - 9, comments - 0, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理
base class constructors execute before derived class constructors, derived class data members have not been initialized when base class constructors run. If virtual functions called during base class construction went down to derived classes, the derived class functions would almost certainly refer to local data members, but those data members would not yet have been initialized.Calling down to parts of an object that have not yet been initialized is inherently dangerous, so C++ gives you no way to do it.

#include <iostream>
#include <string>
#include <cstdlib>
void print(std::string str){std::cout << str<< std::endl;}
class Transaction {
    public:
        Transaction()
        {
            print("Transaction Constructor");
            logTransaction();
        }
        virtual void logTransaction() const // =0;
        {
            print("Transaction Log");
        }
};
class BuyTransaction: public Transaction
{
    public:
        BuyTransaction(){   print("BuyTransaction Constructor");}
        virtual void logTransaction() const
        {
            print("BuyTransaction Log");
        }
};
int main()
{
    BuyTransaction dbc;
    //dbc.logTransaction();
}
pure virtual functions cannot link.
[shangtang@BTSOM-1 study]$ g++ TestT.cpp
TestT.cpp: In constructor 'Transaction::Transaction()':
TestT.cpp:14: warning: abstract virtual 'virtual void Transaction::logTransaction() const' called from constructor
/tmp/ccXFzaHv.o: In function `Transaction::Transaction()':
TestT.cpp:(.text._ZN11TransactionC2Ev[Transaction::Transaction()]+0x7f): undefined reference to `Transaction::logTransaction() const'
collect2: ld returned 1 exit status
virtual function can compile, run, but with surprise result
[shangtang@BTSOM-1 study]$ ./a.out
Transaction Constructor
Transaction Log
BuyTransaction Constructor

The only way to avoid this problem is to make sure that none of your constructors or destructors call virtual functions on the object being created or destroyed and that all the functions they call obey the same constraint.

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理