Re: questions about dynamic binding
On May 12, 11:03 pm, James Kanze <james.ka...@gmail.com> wrote:
Many thanks. Regarding your example:
class A
{
public:
A* clone() const
{
A* result = doClone() ;
assert( typeid( *result ) == typeid( *this ) ) ;
return result ;
}
Why do you need to check typeid? "clone" isn't virtual, then will the
correct version be called if I try to "clone" a B object? Is it true
that if a non-virtual function (here "clone") calls a virtual function
(doClone),then the caller function is automatically virtual?
private:
virtual A* doClone() const
// Except that usually, this will be pure virtual.
// It's fairly rare to have virtual functions in a
// base class which aren't pure virtual.
{
return new A( *this ) ;
}
} ;
Why is it necessary to have another virtual function here that is also
private? What if I put this line of code into "clone()"?
class B
{
private:
virtual A* doClone() const
{
return new B( *this ) ;
}
} ;
If I have a B object "b", then if I do "b.clone()", then "A"'s clone()
method will be called, is it right? I guess what happens next is that
A's clone() calls "doClone()", since this is virtual, then B's
doClone" is called.
I'm still not sure why doClone is needed. Would it work if I do:
class A
{
public:
virtual A* clone() const
{
A* result = new A(*this) ;
assert( typeid( *result ) == typeid( *this ) ) ;
return result ;
}
};
class B
{
B* clone() const
{
return new B( *this ) ;
}
} ;
Thanks,
Jess