Re: why make non-pure virtual functions?

From: Pete Vidler (pvidler_at_mailblocks.com)
Date: 03/15/04


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



Relevant Pages

  • Re: OT: CoolIris releases PicLens 1.6 for Firefox Mac & Win
    ... Class B inherits from A and overrides the virtual method foo introduced ... what if Foo is deleted from the base class? ... The base class doesn't have a Bar, ... you'll get a compile time error. ...
    (borland.public.delphi.non-technical)
  • a subtle change in behavior...
    ... 'public' access with 'public' and the code would still compile. ... the access of a virtual method defined in a base class. ... to create derived classes with the virtual method polymorphed as 'protected' ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Brian Kernighan, maybe Im not worthy, maybe Im scum
    ... and answer A modifies the value of x. ... within the class of which the function is a member. ... Base_class is an object of the base class? ...
    (comp.programming)
  • Re: Drawing a line
    ... The place where you create new classes is where you specify the base class, ... How do I create a "subclass" of CStatic? ... if you want a "line" that is 256 pixels long where each pixel ...
    (microsoft.public.vc.mfc)
  • strange performance of nested virtual methods
    ... I wanted to decorate the features of a base class by declaring a ... virtual method and deriving a new class, ... calling time per nesting level is very irregular. ...
    (microsoft.public.dotnet.framework.performance)