Re: why make non-pure virtual functions?
From: Pete Vidler (pvidler_at_mailblocks.com)
Date: 03/15/04
- Next message: Claudio Puviani: "Re: How did C++ beat the competition?"
- Previous message: Jonathan Turkanis: "Re: What is the proper way to declare an stl stack."
- In reply to: jeffc: "Re: why make non-pure virtual functions?"
- Next in thread: jeffc: "Re: why make non-pure virtual functions?"
- Reply: jeffc: "Re: why make non-pure virtual functions?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 15 Mar 2004 19:50:04 +0000
jeffc wrote:
[snip]
>>Right. I think it would have been better to require the virtual keyword
>>in all the derived classes. If you don't specify 'virtual' in the
>>derived class, and someone looks at that class's header, he won't know
>>which of the member functions are re-implementations of virtual member
>>functions. He would first have to go up the inheritance tree and search
>>through all the base classes to find that out.
[snip]
> void f() {
> cout << "A::f" << endl;
> }
[snip]
You have to specify it as virtual in the base class. If it's left out in
the *derived* class there is no difference. Example:
#include <iostream>
using namespace std;
struct A
{
virtual void foo() { cout << "A::foo" << endl; }
};
struct B : public A
{
/*virtual*/ void foo() { cout << "B::foo" << endl; }
};
int main()
{
A* a = new B;
a->foo();
delete a;
}
Personally I think the C# system is better.. the first class to define a
virtual method marks it "virtual" subsequent overrides in derived
classes must be marked "override". This prevents accidents where you
intended to create a new virtual method but didn't notice there was one
with the same name in a base class.
Also in c#, if you actually meant to hide the base class virtual method
(instead of overriding), you can do so by adding "new"... so it would be
"new virtual". I think the "new" thing is needed whenever you write a
derived method that hides the base one.
-- Pete
- Next message: Claudio Puviani: "Re: How did C++ beat the competition?"
- Previous message: Jonathan Turkanis: "Re: What is the proper way to declare an stl stack."
- In reply to: jeffc: "Re: why make non-pure virtual functions?"
- Next in thread: jeffc: "Re: why make non-pure virtual functions?"
- Reply: jeffc: "Re: why make non-pure virtual functions?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|