Re: Possible to require overloading of a non-pure method?
On Apr 25, 5:58 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
Thomas J. Gritzan wrote:
[rob desbois] schrieb:
On Apr 25, 12:46 pm, Pete Becker <p...@versatilecoding.com> wrote:
On 2008-04-25 06:40:20 -0400, "[rob desbois]"
<rob.desb...@gmail.com> said:
Hi all, I have a set of classes which implement the virtual
constructor idiom.
I had a slicing problem which resulted when I forgot to override
the clone() function in a derived class.
Is there something (other than documentation) that I can do to
prevent this from happening again?
Unit testing and code reviews.
Allow me to clarify. I meant is there any language
construct which can enforce this requirement.
A unit test wouldn't have helped -- I'd have had to
remember to write a unit test for the new class's clone()
method ensuring that the returned pointer is castable to a
pointer to the new derived type. If I'd have remembered
that I'd have remembered to code the clone method anyway.
"Design by Contract".
(That should be "Programming by Contract" here. It's a coding
issue, not a design issue.)
Something like (untestet):
class Base
{
public:
Base* clone() const
{
Base* p = doClone();
assert(typeid(*p) == typeid(*this));
return p;
}
private:
Base* doClone() const
{
return new Base(*this);
}
} ;
First off, no virtual functions here, did you mean to make
'doClone' virtual?
Obviously.
And second, he needed the compile-time solution, AIUI.
You take what you can get:-).
I think I'm the one who actually invented this technique, at
least with regards to using typeid for cloning. In practice,
however, I find that this particular bit of programming by
contract is simply not worth the extra work (although I tend to
use programming by contract fairly intensively in my work
otherwise). As Pete has said, failing to provide the clone
function is something that simply doesn't slip past code review
and unit tests.
And how does 'typeid' trick work? Does 'typeid' return the dynamic
type of '*this'?
It will if the static type is polymorphic.
So, if you derive from 'Base', what then? How does the
splitting of the function in two help _forcing_ the derived
class provide the override?
You get an assertion failure if you attempt to clone a class
which has not implemented the clone function.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34