Re: Possible to require overloading of a non-pure method?
Victor Bazarov schrieb:
Thomas J. Gritzan wrote:
[rob desbois] schrieb:
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?
"Design by Contract".
Something like (untestet):
class Base
{
public:
Base* clone() const
{
Base* p = doClone();
assert(typeid(*p) == typeid(*this));
return p;
}
private:
Base* doClone() const
virtual Base* doClone() const
{
return new Base(*this);
}
}
;
First off, no virtual functions here, did you mean to make 'doClone'
virtual? And second, he needed the compile-time solution, AIUI.
First: Yes, I forgot the virtual. That's what code review is for :-)
Thanks for that.
Second, there is no compile-time solution for this. You can't force to
override a virtual function.
And how does 'typeid' trick work? Does 'typeid' return the dynamic
type of '*this'? 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?
Having a polymorphic class (a class with virtual functions is
polymorphic), typeid(x) returns the dynamic type of x.
In the expression
assert(typeid(*p) == typeid(*this));
typeid(*this) returns the dynamic, run-time type of the current object,
typeid(*p) return the dynamic type of the new object. So, if the clone
doesn't have the exact same type as the current object, the
postcondition of the clone() method is violated.
--
Thomas