Cook Computing

Private Virtual Functions

July 15, 2002 Written by Charles Cook

When trawling through a backlog of over 1000 unread postings to the .NET list I was interested by the thread starting at this item. Quote: "i was just toying around, porting some c++ code to c#, and i discovered that private virtual member functions are not supported."

As later items state, private virtual functions are supported by the CLR. MC++ does support this feature but not C#, so one more to add to the list of features supported by MC++ but not C# (but its not the feature I was hinting about yesterday).

I tested this with the following code. This managed C++ code works as expected:


__gc class Parent
{
public:
  void Bar()
  {
  Foo();
  }
private:
  virtual void Foo() 
  {
    Console::WriteLine(S"Parent::Foo");
  }
};

__gc class Child : public Parent
{
private:
  void Foo() 
  {
    Console::WriteLine(S"Child::Foo");
  }
};

void _tmain(void)
{
  Parent* parent = new Child();
  parent->Bar();
}

but this C# code doesn't even compile:


class Parent
{
  public void Bar()
  {
    this->Foo();
  }

  private virtual void Foo() 
  {
    Console.WriteLine("Parent::Foo");
  }
}

class Child : Parent
{
  <font color="red">private virtual void Foo()</font> 
  {
    Console.WriteLine("Child::Foo");
  }
}

The concept of private virtual functions was completely new to me and seemed strange at first, but they do make sense where functionality must be completely specific to a class (and so not callable from a derived class) even when a pointer to a base class is being used.