Re: omission of "virtual" in overridden method declarations in derived classes
On Feb 23, 6:22 am, "Marco Nef" <maill...@shima.ch> wrote:
Or is the virtuality inherited implicitly from the root of the
inheritance tree even if it is omitted in intermediate classes?
Yes. C++ does not require the programmer to repeat the 'virtual' keyword
for a virtual method in a derived class.
Which is one of the worst "features" of C++ in large projects, as it causes
lots of errors (how do you know that a method is virtual if it is not
written in the declaration of the class you are working with?). It should
also be that base methods can only be called in the direct base class, or
the programmer has to explicitly write a cast to skip a hierachy level.
Some time ago I asked to change this in the new standard, so that virtual
must be repeated in derived classes. But the reply in this group was that
lots of old code would not compile anymore. That was a bad answer, as
compilers could have a flag to ignore such an additional security feature in
old code...
- Marco
A better answer is really "because C++ is not Java." virtual can be
used to implement an OO design, but in and of itself is just an
implementation detail, and does not always mean "dynamic polymophism
on an object."
But C++0x will have flags to do what you are asking. See
http://en.wikipedia.org/wiki/C%2B%2B0x in the "Explicit virtual
function overrides" section.
There are good reasons not to repeat the virtual keyword. Say I had a
classes
struct null{};
struct vallcoator{
virtual void * allocate(unsigned sz)=0;
virtual deallocate(void*)=0;
~vallcoator(){};
};
struct vvallcoator:virtual vallcoator{
};
template<class Base>
struct allocator:Base{
void * allocate(unsigned sz){return malloc(sz);}
void deallocate(void*p){free(p);}
};
Now I have a peice of code that is suitable as a
1. allocator<null> a;//standalone object
2. vallcoator* v=new allocator<vallcoator>;//SI polymorphic object
3. struct valloc:virtual vallcoator,protected
allocator<vvallcoator>{};
vallcoator* v=new valloc;//mixin object
while honoring "you dont pay for what you dont use" and the "dont
repeat yourself" rules. If struct allocator was also forced to say
"virtual" then this example of policy based design (not OO design)
would be much more difficult.
But I will agree that in the vast majority of C++ code, there should
be some mechanism to check that what you intended to override, hide,
etc is actually what happened, and the new standard provides that.
Lance
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]