PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 26, 2022

[FIXED] Why a function with protected modifier can be overridden and accessible every where?

 October 26, 2022     access-modifiers, c#, d, oop     No comments   

Issue

I'm C# programmer new to D language. I'm a bit to confused with OOP in D programming language.

Assuming that I have the following class:

public class A {
   protected void foo() {
      writefln("A.foo() called.");
   }
};

public class B : A {
   public override void foo() {
      writefln("B.foo() called.");
   }
};

The protected modifier means that I can access the .foo() method just on inherited class,so why this D program compiles normally?

Here is the equivalent to C#.NET:

using System;

public class A {
   protected virtual void foo() {
      Console.WriteLine("a.foo() called.");
   }
};

public class B : A {
   public override void foo() {
      Console.WriteLine("b.foo() called.");
   }
};

public class MainClass  {
   public static void Main(string[] args) {
      A a = new A();
      B b = new B();    
      a.foo();
      b.foo();
   }
};

It don't compiles and given the following error message(as I expected):

test.cs(10,30): error CS0507: B.foo()': cannot change access modifiers when overridingprotected' inherited member `A.foo()'

Can someone explain this D behavior? Thanks in advance.


Solution

There's no purpose in preventing the override. The derived class could implement a trivial forwarding function that allows access. Consider:

public class A {
    protected virtual void foo() {
        writefln("A.foo() called.");
    }
};

public class B : A {
   protected override void foo() { // OK
       writefln("B.foo() called.");
   }
   public void call_foo() {
       foo(); // But I allowed public access anyway!
   }
};

Thus, even though I didn't redefine the access level of foo, I still allowed public access to it and there's nothing you can do about it. Allowing the redefinition is just simpler.



Answered By - Puppy
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing