Re: Copy of derived object from pointer to base

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: Larry Brasfield (donotspam_larry_brasfield_at_hotmail.com)
Date: 10/12/04


Date: Tue, 12 Oct 2004 09:37:43 -0700


"Sigurd Stenersen" <sigurds@utvikling.com> wrote in message news:%237Po%23fHsEHA.3588@tk2msftngp13.phx.gbl...
> Larry Brasfield wrote:
>> "Sigurd Stenersen" <sigurds@utvikling.com> wrote in message
>>> class Base
>>> {
>>> public:
>>> virtual Base *Clone() { return new Base(*this); }
>>> };
>>>
>>> class Derived : public Base
>>> {
>> #if 0
>>> virtual Base *Clone() { return new Derived(*this); } #endif
>>
>> virtual Derived *Clone() { return new Derived(*this); }
>>> };
>>
>> The reason to return a pointer whose type is pointer to the
>> derived class is to make the Clone() method usable, without
>> casting, when the result is known to be a subclass of Base.
>
> Sure, but that doesn't work on all compilers.

It works on all C++ compilers, (where 'C++' is as defined
by the current ISO standard).

> It certainly doesn't work on
> mine (VS6). Is it really legal C++ ?

Yes. There is even a name for this relationship among
methods along a class hierarchy, but I've forgotten it.

>> Proper support of this long time C++ feature came late
>> to MSVC++, arriving with v7.
>
> Ah, well. Does it allow for any return type, or just derived return types ?

The return type has to have the original (base) virtual
method's return type as a base class.

-- 
--Larry Brasfield
email: donotspam_larry_brasfield@hotmail.com
Above views may belong only to me. 


Relevant Pages

  • Re: Copy of derived object from pointer to base
    ... > The reason to return a pointer whose type is pointer to the ... > derived class is to make the Clone() method usable, ...
    (microsoft.public.vc.language)
  • Re: Virtual Data?
    ... > pointer to function. ... type of data for a member variable of the same name, ... But your derived class needs a more complicated variable x, ... virtual Init(const int initX); ...
    (comp.lang.cpp)
  • dynamic_cast problem
    ... I am having problems calling dynamic_caston a pointer returned by a ... The library contains a base class and a derived class and also an extern "C" ... function that returns a pointer ... class Destination_tib: public DestinationImpl { ...
    (comp.lang.cpp)
  • Re: Un-ringing the bell: making parent methods unavailable to children
    ... course making the method private in the derived class will prevent it from ... > to one type of data structure as a pointer to another type via overriding ... > Addunless it is type case as its parent class. ... > polymorphism in general. ...
    (microsoft.public.dotnet.languages.vc)
  • Re: inheritance
    ... > constructors of a base class are not also members of the derived class. ... side is _converted_ to A* using the standard "pointer to derived to pointer ... to base" conversion. ...
    (comp.lang.cpp)