-3

I am wondering what would theoretically be the output of this code? Basically I am overwriting a method in the child class but I am calling that method in the parent class. I am hoping the output of this would be "Child"

public class Animal {
    protected virtual void Activate() {
        Debug.Log("Parent");
    }

    void CallStuff() {
        Activate();
    }
}

public class Frog : Animal {
    override void Activate() {
        Debug.Log("Child");
    }
}

If I were to have a frog instance frog and call ...

frog.CallStuff();

What would the output be?

Patrick
  • 1,717
  • 7
  • 21
  • 28
user3312266
  • 187
  • 1
  • 4
  • 14

2 Answers2

1

the output would be "Child" It inherited the Call Stuff function but overrode the Activate function so you'd get Child

chris-crush-code
  • 1,114
  • 2
  • 8
  • 17
1

Perhaps some examples will explain best:

Let's start with a base class:

public class Parent {
  public virtual string WhatAmI() {
    return "Parent";
  }

  public string Output() {
    return this.WhatAmI();
  }
}

Calling the Output method will, of course, give you "Parent"

new Parent().Output(); // "Parent"

Now let's override that virtual method

public class OverridingChild : Parent {
  public override string WhatAmI() {
    return "Child";
}

Now when you call Output(), it returns "Child"

new OverridingChild().Output(); // "Child"

And if you cast it to a Parent, you get the same result:

((Parent) new OverridingChild()).Output(); // "Child"

If you want the base class's value, you have to call base from within the inheriting class:

public class OverridingChild : Parent {
  public override string WhatAmI() {
    return "Child";

  public string OutputBase() {
    return base.WhatAmI();
  }
}

new OverridingChild().OutputBase(); // "Parent"

Now for the confusing bit - here's how you can get either value, depending on what class the compiler thinks the object is:

public class NewMethodChild : Parent {
  // note that "new" keyword
  public new string WhatAmI() {
    return "Child";
}

Calling the method directly when the compiler thinks it's the inheriting class gets you the expected result:

new NewMethodChild().WhatAmI(); // "Child"

But if you cast it to the base class, you get the Parent result:

((Parent) new NewMethodChild()).WhatAmI(); // "Parent"

And if you call the Output method, because it is defined at the Parent class it doesn't see the new WhatAmI method of the inheriting class, so it also outputs the base value:

new NewMethodChild().Output(); // "Parent"

Hope that clears things up.

PhilChuang
  • 2,556
  • 1
  • 23
  • 29