Re: derived class and virtual function
Stefan van Kessel <stefan.van.kessel@mytum.de>, on 13/08/2010 10:51:30,
wrote:
On 8/13/2010 10:29 AM, subramanian100in@yahoo.com, India wrote:
In Stanley Lippman's 'C++ Primer Fourth Edition', in page 564, the
following is mentioned:
"A virtual function in the derived class can return a reference or
pointer to a class that is PUBLICLY derived from the type returned by
the base class function."
I am unable to understand this sentence. Kindly explain it with
program sample.
Thanks
V.Subramanian
It allows you for example to write code like this (polymorphic copy)
#include <iostream>
class Foo
{
public:
virtual Foo* createCopy(){ return new Foo(*this); }
virtual void quack() { std::cout<<"I'm a foo"<<std::endl; }
virtual ~Foo(){}
};
class Bar : public Foo
{
public:
// notice that this createCopy returns a Bar* instead of Foo*
// which is a "pointer to a class that is PUBLICLY derived"
virtual Bar* createCopy(){ return new Bar(*this); }
virtual void quack() { std::cout<<"I'm a bar"<<std::endl; }
};
int main() {
Bar bar;
Foo& br = bar;
Foo* bp = br.createCopy();
bp->quack();
delete bp;
}
Ah, this makes more sense than my example, but I've been able to make it
work even declaring Bar::createCopy() as non-virtual, just for the records.
--
FSC - http://userscripts.org/scripts/show/59948
http://fscode.altervista.org - http://sardinias.com