Quiz on C++ Object Model
Posted on March 4th, 2010 at 0:07 by fr3@K

這幾個月忙於工作, 這個部落格都快被我給荒廢掉了. 昨晚終於花了時間完成了一篇積了一兩個月, 說明 virtual function 在執行時期的 override 過程以及 virtual function 與 constructor/destructor 混搭結果 的文字.

今天我準備了個題目給花了時間看了它的朋友, 當作對小弟的說明能力來個測驗. 請問, 下面的 code snip 的輸出結果是什麼?

C++:
  1. #include <typeinfo>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. struct Base
  7. {
  8.   Base()
  9.   {
  10.     this->print_type_name();
  11.   }
  12.   virtual void print_type_name()
  13.   {
  14.     cout <<typeid(*this).name() <<endl;
  15.   }
  16. };
  17. struct Derived : Base
  18. {
  19. };
  20.  
  21. int main()
  22. {
  23.   Derived d;
  24.   d.print_type_name();
  25.   return 0;
  26. }

也就是說, 對同一個, 沒有被 override 過的 virtual function - Base::print_type_name - 呼叫兩次 (第一次是透過 Base 的 ctor 間接呼叫, 第二次則是當 Derived 的 object instance 直接呼叫) 的輸出是什麼? And why?

有些事情, 可以是做爽的. 而這些文字除了幫助降低自己 (主要是在工作上) 對相同主題重複一再說明的負擔, 它們還蘊藏著我的理想性 - 我衷心期望它們能夠對華文技術圈有所助益. 也希望我的說明能力不要太差, 讓這些文字淪落到寫爽的.

Hope you have fun while figuring out the quiz.

del.icio.us:Quiz on C++ Object Model digg:Quiz on C++ Object Model spurl:Quiz on C++ Object Model newsvine:Quiz on C++ Object Model furl:Quiz on C++ Object Model Y!:Quiz on C++ Object Model 黑米共享書籤:Quiz on C++ Object Model 推推王:Quiz on C++ Object Model
Previous Post
« 當 Constructor 遇上 Virtual Function «
Next Post
» Pic of starryalley on iThome »

1 Comment »

Comment #11986

不考慮 compiler 怎麼 encode type name 。印出:Base 再印出 Derived 。

因為當 Constructor 遇上 Virtual Function說:
建構一個 Derived 的 object instance 時, 先被建構的是其父類別,因此此時 typeid 會是拿到 Base class 。待子類別建構完成後、在 main() 中的 d.print_type_name(); 呼叫才會拿到 Derived 。

Comment by Keiko — March 4, 2010 @ 13:46


Comments RSS TrackBack URI

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>