home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / cplus / 11614 < prev    next >
Encoding:
Text File  |  1992-07-27  |  1.9 KB  |  77 lines

  1. Path: sparky!uunet!sun-barr!ames!agate!dog.ee.lbl.gov!ucbvax!DCC.UNICAMP.BR!mauricio
  2. From: mauricio@DCC.UNICAMP.BR (Mauricio Fernandez)
  3. Newsgroups: comp.lang.c++
  4. Subject: Assigning a derived class to a base class.
  5. Message-ID: <9207271226.AA03664@dcc.unicamp.br>
  6. Date: 27 Jul 92 18:07:11 GMT
  7. Sender: daemon@ucbvax.BERKELEY.EDU
  8. Lines: 66
  9. X-Unparsable-Date: Mon, 27 Jul 92 9:26:51 GMT-3:00
  10.  
  11. Hello, I'm posting this message through e-mail since I have no direct
  12. access  to usenet. I guess the following topic has already been
  13. discussed in this group.
  14.  
  15. Suppose you have a base class B with some virtual function F.
  16.  
  17. class B{ ...
  18.  
  19. virtual F();
  20.  
  21. }
  22.  
  23. and a derived class from B that redefines F.
  24.  
  25. class D:B{... (or class D: public B{...)
  26.  
  27. F();
  28.  
  29. }
  30.  
  31. Now, when you assign an instance of class D to a variable declared to
  32. be of type B the assigned variable holds a pure B instance, this means
  33. that F calls will be resolved to the base class code.
  34.  
  35. This turns out to be dramatic in the following case. You want to build
  36. a linked list supporting different types (a single instance of the
  37. list should have nodes of different types) so you create a generic
  38. node
  39.  
  40. class generic_node{
  41.     generic_node *next, *previous;
  42. public:
  43.     virtual void Print(){
  44.         cout << "Sorry, I have no value to print for you\n";
  45.     }
  46. };
  47.  
  48. And then you create the specific node types
  49.  
  50. class int_node:public generic_node{
  51.     int value;
  52. public:
  53.     virtual void Print(){
  54.         cout << value << '\n';
  55.     }
  56. };
  57.  
  58. class string_node:public generic_node{
  59.     char *str;
  60. public:
  61.     virtual void Print(){
  62.         cout << value << '\n';
  63.     }
  64. };
  65.  
  66. This works ok as long as I don't try to make a copy of a list.
  67. Is there an elegant way to cope with this? I couldn't arrive to 
  68. a satisfactory solution. 
  69.  
  70. Please, reply-me via e-mail. Thanks in advance.
  71.  
  72. ___________________________________________________________________
  73.                                                 Mauricio Fernandez
  74.                                            mauricio@dcc.unicamp.br
  75.  
  76.  
  77.