2

I don't quite understand the modifiernew in C#: In which way is the following code different depending on the presence of the new modifier?

class A 
    {
        public void F() { Console.WriteLine("A::F()"); }
    }


class B : A
    {
    public new void F() { Console.WriteLine("B::F()"); }

    public static void Main()
    {
        A a = new B();
        B b = new B();
        A trueA = new A();
        a.F();
        b.F();
        trueA.F();
        Console.ReadLine();
    }
}

Is there any equivalent or similar thing in C++?

Haney
  • 32,775
  • 8
  • 59
  • 68
José D.
  • 4,175
  • 7
  • 28
  • 47
  • 1
    I think you meant [new operator](http://msdn.microsoft.com/en-us/library/fa0ab757.aspx) – Habib Jan 23 '14 at 17:44
  • @Habib Given that the code won't even compile if the `new` operator was removed, I think OP means the `new` modifier. – p.s.w.g Jan 23 '14 at 17:46
  • @p.s.w.g, I think the code would compile but it will only give a warning for method hiding. And yes you are right the OP is asking about method hiding and not the new operator. – Habib Jan 23 '14 at 17:47
  • 1
    Are you asking why `a.F` and `trueA.F()` both return `"A::F()"`, even though `a` is instantiated as `new B()`? I don't quite get the question. – Jodrell Jan 23 '14 at 17:57
  • Second part (C++ equivalent of C# "new modifier") is covered in [Can you Hide a virtual method in c++](http://stackoverflow.com/questions/1828009/can-you-hide-a-virtual-method-in-c) – Alexei Levenkov Jan 23 '14 at 18:13

2 Answers2

4

The result is the same if you are using public void F() or public new void F() in the class B. The method will still be shadowed.

The difference is that if you omit the new modifier, you will get a compiler warning because the code may be confusing. The new modifier is used to specify that you actually intended to shadow a member from the base class, and didn't just happen to use the same name by mistake.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

You would see differences if you defined in the base class the method virtual. The override modifier extends the base class method, and the new modifier hides it by creating a new method which has nothing to do with one on the base class. Try next code :

class Program
{
 class A
 {
   public virtual void F() { Console.WriteLine("A::F()"); }
   public virtual void G() { Console.WriteLine("A::G()"); }
 }


class B : A
{
  public override void F() { Console.WriteLine("B::F()"); }
  public new void G() { Console.WriteLine("B::G()"); }

  public static void Main()
  {
    A a = new B();
    B b = new B();
    a.F();
    b.F();
    a.G();
    b.G();

    Console.ReadLine();
  }
}

}

In C++ you can hide a method of the base class by defining a method on the derived class with the same name but different parameters. Maybe you can use that.