0

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.

Tom
  • 673
  • 4
  • 12
  • 20
  • Please add the class definition inheritance schema and use of virtual keyword may change the behavior of your exemple. – VGE May 10 '11 at 11:53
  • It doesn't look like it's a very good book. Maybe you could find a different one with some more useful examples? – Stu Mackellar May 10 '11 at 11:55

3 Answers3

3

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.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • @Hassan: I added an explanation. A more detailed one can be found in the excellent answer I linked. – Björn Pollex May 10 '11 at 12:02
  • Thank you a lot. It helps me. The book mention the Slicing in two words, and I can't understand what it means. – Tom May 10 '11 at 12:06
  • Slicing has nothing to do with design it is a physical side effect of C++ semantics. It is also an ellusive concept to grasp especially when placed in the context of all the other features of C++ (multiple inheritance). A more sound answer should enhance understanding in as general a way as possible. – Hassan Syed May 10 '11 at 12:14
0
Window win 

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

onurozcelik
  • 1,214
  • 3
  • 21
  • 44
0

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.

Hassan Syed
  • 20,075
  • 11
  • 87
  • 171