Ilocker: Focus on Android Security (novice) qq:2597294287
1 classTransaction {//base class for all transactions2 Public:3 Transaction ();4 Virtual voidLogtransaction ()Const=0;//make a different type of log record5 ... ..6 }7 transaction::transaction () {8 ... ..9 logtransaction ();Ten}
Derived class:
1 classBuytransaction: PublicTransaction {2 Public:3 Virtual voidLogtransaction ()Const;4 ... ..5 }6 classSelltransaction: PublicTransaction {7 Public:8 Virtual voidLogtransaction ()Const;9 ... ..Ten}
Now execute:
1 buytransaction b;
The base class part of the derived class object is first constructed, so the Transaction constructor is called first. The logtransaction that is called in the Transaction constructor is the version of Transaction, not the version of Buytransaction, even if the object type being created is buytransaction.
During the base class construct, the virtual function will never descend to the drived classes hierarchy, because the member variable of drived class is not initialized yet, and if the virtual function accesses an uninitialized member variable, it will result in ambiguous behavior, C + + forbid This dangerous operation.
More specifically: During the base class construction of the derived class object, the object type is the base class, not the derived class, which is also valid for RTTI (such as dynamic_cast, typeID).
In the same way, when the destructor of the base class is executed, the destructor of the derived class is executed, the member variables of the derived class render undefined values, and C + + sees them as non-existent, when the object is a base class object.
In the example, the constructor calls the virtual function directly, and you should also note that the constructor and destructor have no indirect calls to the virtual function.
Learning materials: "Effective C + +"
C + + notes (ii)--Do not call virtual functions in constructs and destructors