home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!sun-barr!ames!agate!dog.ee.lbl.gov!ucbvax!DCC.UNICAMP.BR!mauricio
- From: mauricio@DCC.UNICAMP.BR (Mauricio Fernandez)
- Newsgroups: comp.lang.c++
- Subject: Assigning a derived class to a base class.
- Message-ID: <9207271226.AA03664@dcc.unicamp.br>
- Date: 27 Jul 92 18:07:11 GMT
- Sender: daemon@ucbvax.BERKELEY.EDU
- Lines: 66
- X-Unparsable-Date: Mon, 27 Jul 92 9:26:51 GMT-3:00
-
- Hello, I'm posting this message through e-mail since I have no direct
- access to usenet. I guess the following topic has already been
- discussed in this group.
-
- Suppose you have a base class B with some virtual function F.
-
- class B{ ...
-
- virtual F();
-
- }
-
- and a derived class from B that redefines F.
-
- class D:B{... (or class D: public B{...)
-
- F();
-
- }
-
- Now, when you assign an instance of class D to a variable declared to
- be of type B the assigned variable holds a pure B instance, this means
- that F calls will be resolved to the base class code.
-
- This turns out to be dramatic in the following case. You want to build
- a linked list supporting different types (a single instance of the
- list should have nodes of different types) so you create a generic
- node
-
- class generic_node{
- generic_node *next, *previous;
- public:
- virtual void Print(){
- cout << "Sorry, I have no value to print for you\n";
- }
- };
-
- And then you create the specific node types
-
- class int_node:public generic_node{
- int value;
- public:
- virtual void Print(){
- cout << value << '\n';
- }
- };
-
- class string_node:public generic_node{
- char *str;
- public:
- virtual void Print(){
- cout << value << '\n';
- }
- };
-
- This works ok as long as I don't try to make a copy of a list.
- Is there an elegant way to cope with this? I couldn't arrive to
- a satisfactory solution.
-
- Please, reply-me via e-mail. Thanks in advance.
-
- ___________________________________________________________________
- Mauricio Fernandez
- mauricio@dcc.unicamp.br
-
-
-