Path: utzoo!attcan!uunet!cs.utexas.edu!tut.cis.ohio-state.edu!ucbvax!hplabs!hplabsz!bs From: bs@hplabsz.HPL.HP.COM (Bob Shaw) Newsgroups: comp.lang.c++ Subject: Return types of virtual member functions Message-ID: <3403@hplabsz.HPL.HP.COM> Date: 27 May 89 01:01:19 GMT Organization: Hewlett-Packard Laboratories Lines: 94 I'm trying to build a "bushy" single inheritance tree. Many of the child classes define a few member functions beyond those of the parent. Most of the system deals with the various objects at the highest level of abstraction (i.e. only use the parent member functions), but parts of the system change the level of abstraction and deal with the object as an instance of a child class. My question involves the return value types in virtual member functions. If a parent class defines a virtual member function such as virtual parent* msg(); I would like a child (derived) class to be able to define its version of the member function as virtual child* msg(); rather than virtual parent* msg();. It's my understanding that a child* can always be assigned to something defined as a parent*, so I can't see why this should break the type system. Obviously, children of such a child would be constrained to return a pointer to child or something derived from it. The code below does not work as I had hoped. Can someone involved in the ATT C++ 2.0 release tell me if this will work in 2.0 and, if not, whether it's a bug or why it isn't a reasonable thing to do? Thanks, bs <- obviously not the att one ---------------------------- Output from following code: parent->msg() parent::msg entered child->msg() child::msg entered child_as_parent->msg() parent::msg entered <---- I'd hoped for "child::msg entered" ---------------------------- #include class parent { public: virtual parent* msg(); }; class child : public parent { public: virtual child* msg(); }; parent* parent::msg() { cout << " parent::msg entered\n"; return this; } child* child::msg() { cout << " child::msg entered\n"; return this; } void main() { parent* presult; child* cresult; parent* p = new parent; child* c = new child; cout << "\nparent->msg()\n"; presult = p->msg(); cout << "\nchild->msg()\n"; cresult = c->msg(); cout << "\nchild_as_parent->msg()\n"; p = c; presult = p->msg(); }