J
J
Jypsy2018-11-21 10:42:00
C++ / C#
Jypsy, 2018-11-21 10:42:00

How will the override work?

Please explain why A is displayed in the console.
After all, if I understand everything correctly, in this line A ac = new C(); those methods that class A has are called (since this is the type of the variable), but their implementation will be called from C, that is, it will display C.

using System;
using System.Collections.Generic;
using System.IO;
namespace ProjectOne {
  public abstract class A{
    public virtual string Print(){
      return "A";
    }
  }
  public class B:A{
    public virtual new string Print(){
      return "B";
    }
  }
  public class C:B{
    public override string Print(){
      return "C";
    }
  }
  class EntryPoint {
    static void Main(string [] args){
    A ac = new C();
    Console.WriteLine (ac.Print());
    }

  }}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Pavlov, 2018-11-21
@Jypsy

In class A, the Print method is marked virtual, that is, it can be overridden. But in the successor of B there is no redefinition of this method, but a new virtual method with the same name is created - the new keyword indicates that a new method is being created that is not associated with the A.Print method.
In class C, the Print method overrides the parent method, that is, the B.Print method, but does not override the A.Print method.
Since the variable has type A, the call to ac.Print() will call the method - the only one of the implementations of the A.Print method.
See here to make it clearer:

class A { public virtual void Print() { Console.WriteLine("A"); } }
class B : A { public override void Print() { Console.WriteLine("B"); } }
class C : B { public new virtual void Print() { Console.WriteLine("C"); } }
class D : C { public override void Print() { Console.WriteLine("D"); } }

A ad = new D();
ad.Print(); // покажет B

F
Fat Lorrie, 2018-11-21
@Free_ze

The method is marked virtual (virtual), so the compiler substitutes the code of the virtual method call (the IL instruction callvirt), and not the direct one (call). In dotnet, every object has an implicit reference to its corresponding (real) type object. Through this link is the address of the correct method.
In other languages, things may be arranged differently. And you can read more about the dotnet device in Jeffrey Richter's book "CLR via C#..." .

O
OREZ, 2018-11-21
@OREZ

virtual new "breaks" the chain of method overrides, so the base type will be called on the last one in the chain of overrides before the first one "broken"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question