I think you can and my colleage thinks you cannot!
Virtual methods can be overridden in the derived class, but it is not mandatory like abstract methods. Virtual methods cannot be private in C#. All the virtual methods must have to provide the body definition in C#.
You can override virtual functions defined in a base class from the Visual Studio Properties window.
A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class.
They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. A class may have virtual destructor but it cannot have a virtual constructor.
You can't even declare private virtual methods. The only time it would make any sense at all would be if you had:
public class Outer
{
private virtual void Foo() {}
public class Nested : Outer
{
private override void Foo() {}
}
}
... that's the only scenario in which a type has access to its parent's private members. However, this is still prohibited:
Test.cs(7,31): error CS0621: 'Outer.Nested.Foo()': virtual or abstract members cannot be private
Test.cs(3,26): error CS0621: 'Outer.Foo()': virtual or abstract members cannot be private
Your colleague is right. You can't declare private virtual methods because there's no point (since there'd be no way to override them)...
But you can override protected virtual methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With