简体   繁体   中英

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 =  txtWinPtr;
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM