It's certainly NOT C++ reasoning!
Suppose this happens:
(1) I call a virtual method in the constructor for a class.
(2) Someone derives a new class from that class.
(3) In the derived class they override the virtual method and do something that assumes that the derived class' constructor has been called.
(4) BANG! It blows up.
The following code demonstrates the problem:
(1) The "Base" class introduces a virtual bool property called "DoubleBuffered".
(2) The "NastyDerived" class sets DoubleBuffered to true in its constructor. That's all it does.
(3) The InnocentDerived class derives from NastyDerived.
It overrides DoubleBuffered, and as part of its implementation uses a value ("NonZeroValue") that should have been set in the constructor.
Seems ok, right? After all, it's been set to 1 in the constructor. So how could it possibly be 0 inside DoubleBuffered?
Anyways, compile and run the program, and you'll see that it blows up with a divide-by-zero exception!
So by setting DoubleBuffered in the constructor, I have caused DoubleBuffered in a derived class to be called before the derived class's constructor has been run. Nasty nasty nasty! Which is why I think it should be avoided.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
InnocentDerived d = new InnocentDerived();
}
}
class Base
{
public virtual bool DoubleBuffered
{
get;
set;
}
}
class NastyDerived: Base
{
public NastyDerived()
{
DoubleBuffered = true;
}
}
class InnocentDerived: NastyDerived
{
public InnocentDerived()
{
NonZeroValue = 1; // Ensure that this can never be zero.
}
public int NonZeroValue // Can never be zero. Set to 1 in the ctor.
{ // ...or so he thinks.
get;
private set;
}
public override bool DoubleBuffered
{
get
{
return base.DoubleBuffered;
}
set
{
base.DoubleBuffered = value;
_specialValue = 100/NonZeroValue;
}
}
private int _specialValue;
}
}