Topic: Calling pure virtual functions in base class constructors/destructor
Author: pabloh@hpwala.wal.hp.com (Pablo Halpern )
Date: Wed, 4 Nov 1992 19:44:31 GMT Raw View
In article <miLRVB10w165w@csource.oz.au>, david@csource.oz.au (david nugent) writes:
|> I'm somewhat puzzled as to why the current rule on calling pure virtual
|> functions from a base class does not simply prohibit them from being
|> there (ie. by a compiler error) rather than defining the results as
|> being 'undefined'. (ARM sec 12.7)
[ some text deleted ]
|> In case I'm being completely obscure or not clear enough in what I'm
|> trying to say, here's an example of what I'm talking about:
|>
|> class A
|> {
|> // ...
|> ~A() { purefunc(); }
|> virtual void purefunc() = 0;
|> };
|>
|> class B
|> {
|> // ...
|> ~B() {};
|> void purefunc () { cout << "foo"; }
|> };
|>
|> void
|> main ()
|> {
|> B o;
|> }
|>
|> This results in very strange behaviour when 'o' is destroyed on exit from
|> main(). Why doesn't the compiler prevent calling purefunc() in class A's
|> destructor?
In the case you showed, the compiler could and *should*, IMHO, at least warn
you of this error. However, the requirement that calling a pure virtual
function from a constructor or destructore be "undefined" allows the
following code:
class A
{
// ...
~A() { normalfunc(); }
void normalfunc();
virtual void purefunc() = 0;
};
class B
{
// ...
~B() {};
void purefunc () { cout << "foo"; }
};
void A::normalfunc()
{
if (someCondition)
purefunc();
// dostuff
}
Notice that purefunc() is being called *indirectly* through normalfunc().
normalfunc() could, of course, be called in other circumstances as well.
In order for the compiler to recognize this situation, it would be
necessary for it to descend the call tree when compiling the constructor or
destructor. Even then, the best it could do is issue a warning, since it
is quite possible that the conditional expression, someCondition, would
never be true within the constructor or destructor, thus making the above
code valid.
To summerize: you are right that, in some circumstances, the compiler could
detect and warn the user about invalid calls to pure virtual functions, but
I don't think they should be *required* to do so.
--
- Pablo
------------------------------------------------------------------------
Pablo Halpern (617) 290-3542
HP Waltham pabloh@hpwarq.wal.hp.com
I am self-employed, so my opinions *do* reflect those of my employer.
However, they may not reflect the opinions of my client.
------------------------------------------------------------------------