开发者

c++ member function binding

I read one of the book which deals with the issues of member function binding in c++.

and it's giving the next example:

void Window::oops()  { printf("Window oops\n"); } 
void TextWindow::oops() { 
printf("TextWindow oops %d\n", cursorLocation);

Window      win; 
Window     *winPtr;
TextWindow *txtWinPrt = new TextWindow; 
win    = *txtWinPrt; 
winPtr =  tx开发者_开发知识库tWinPtr;
win.oops();     // executes Window version 
winPtr->oops(); // executes TextWindow or Window version;

I didn't understand why win.oops would executes window version? win is defined as Textwindow.

Thank you for your help.


This is caused by slicing. If you assign to an object of the super-class, the information from the subclass is lost. The problem is this statement:

win    = *txtWinPrt;

Since you assign an object of a subclass (TextWindow) to an object of the super-class (Window), all the information of TextWindow that is not in Window is sliced away.


Window win 

is an object of Window class. It should be pointer or reference to call derived class method with base class instance.


Two things are needed for dynamic polymorphism using object orientation (which is what you are asking for).

  1. Window and Textwindow need to implement the "is-a" relationship. (so, class TextWindow : public Window {});
  2. A virtual function is needed in a base-clase in order to get runtime polymorphism, generally a destructor if you cannot find a virtual function naturally. A virtual function causes the compiler to put down a v-table.

Without these two things, the compiler will not put a v-table down at callsites. The v-tables enables runtime polymorphism as function calls are indirected through it.

Alternatively you could resort to c-style function pointers, or something like boost::bind. But this defeats OO programming. I personally use a v-table very rarely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜