0

Below code gives me compiler error :

'Rextester.Derived.foo()': cannot change access modifiers when overriding 'public' inherited member 'Rextester.Base.foo()'

Why can't derive class keep the implementation of overridden function private to itself ? This is allowed in Cpp.

One use case i find is to force developer to use Base classes. In working with large code bases, i think this is useful.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    class Base
    {
        public virtual string foo()
        {
            return "hi base";
        }
    }

    class Derived : Base
    {
        protected override string foo()
        {
            return "bye derived";
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Base b = new Derived();

            //Your code goes here
            Console.WriteLine(b.foo());
        }
    }
}

Code link : https://rextester.com/LBQO45364

Ashish Negi
  • 5,193
  • 8
  • 51
  • 95
  • Liskov substitution principle, I imagine. It'd be nice if you could make them more public in derived classes, I guess. – ProgrammingLlama Jun 06 '19 at 05:09
  • 2
    Imagine someone is using it this way `Base obj = new Derived(); obj.foo();`. Just curious, how would it behave in C++ in this case? – Yeldar Kurmangaliyev Jun 06 '19 at 05:10
  • 1
    @YeldarKurmangaliyev I just tried it, and short answer is the derived gets called even though it's private; link at https://rextester.com/CYLFBG75877 – racraman Jun 06 '19 at 05:26

1 Answers1

0

foo() is part of Base's public interface (and its derived classes). Thus you cannot hide it in Derived because it would break this contract.

Spotted
  • 4,021
  • 17
  • 33