Consider this code sample:
public abstract class Parent
{
public int val;
public Parent()
{
val = 0;
}
public virtual void foo()
{
inc();
}
public virtual void inc()
{
val = val + 10;
}
}
public class Child : Parent
{
public override void foo()
{
base.foo();
}
public override void inc()
{
val++;
}
}
static void Main(string[] args)
{
Parent p = new Child();
Console.WriteLine("p.val = " + p.val); //Output: p.val = 0
p.foo();
Console.WriteLine("P.val = " + p.val); //Output: p.val = 1
}
I am assuming the inc()
of the Parent class did not get called because {this}
pointer is actually pointing to a Child object so the Child's version of inc()
will be called from the Parent object's function foo()
. Is there a way to force the Parent's function foo()
to always call parent's function inc()
Like you could in C++ with ::
operator?
No, the only way you can call a virtual method non-virtually is with base.Foo
. Of course, you could write a non-virtual method in Parent
, and make Parent.foo()
call that, as well as the default implementation of Parent.inc()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With