Topic: Virtual functions returning derived class pointers


Author: Paul Parsons <PPARSONS@ESOC.BITNET>
Date: Tue, 1 Mar 1994 17:37:01 CET
Raw View
I took this from comp.object
Can anyone tell me when this feature is likely to be incorporated into
commercial compilers esp. cfront.

Thanks,

Paul

> jjb@watson.ibm.com (John Barton) writes:
>
> I only want to clarify Mark's comments.  The ANSI committee has
> accepted and our compiler implements returning derived class pointers
> in virtual functions whose name and argument types match a base class
> virtual function.  Clients of the base class can use these pointers as
> base class pointers; clients of the derived class can use these
> pointers derived class pointers.
>
> Introducing a virtual function in a derived class with the same name
> as a base class virtual function but different arguments creates an
> overloaded name.  The base class virtual is not overridden, even if
> there is some type relation between the arguments of the two
> functions.  Our compiler, and most others, flags this as an error;
> it usually is an error and arguably always a design flaw for a C++
> program.  To add a virtual function with the same name as a base class
> virtual function, declare both in the derived class and forward the
> one that matchs to the base class.
>
>
> class B {
> public:
>   virtual B* foo(const B&) = 0;
> };
> class D : public B {
> public:
>   virtual D* foo(const B&);  // OK. Overrides B::foo.
> };
>
> D* D::foo(const B&) { return new D(*this); }
>
> int main() {
>   D d;
>   D* pd = d.foo(d);  // d matches const B&
> }
>