Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you override private virtual methods?

Tags:

c#

virtual

I think you can and my colleage thinks you cannot!

like image 438
Barrie Reader Avatar asked Mar 16 '10 16:03

Barrie Reader


People also ask

Is it possible to override a private virtual method in C#?

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#.

Can you override a virtual function?

You can override virtual functions defined in a base class from the Visual Studio Properties window.

Can we override private method in CPP?

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.

Can we override virtual method in C++?

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.


2 Answers

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

like image 113
Jon Skeet Avatar answered Oct 21 '22 10:10

Jon Skeet


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.

like image 41
Justin Niessner Avatar answered Oct 21 '22 12:10

Justin Niessner