Calling both basic and derived methods

in both C # and C ++, is it possible to call both base and derived versions of a method with the same signature instead of overriding the version of the base class?

+1
source share
2 answers

In C #, no if the derived method is an override, but yes if it is marked as new. When using this design, you should be careful, as this is actually not what the consumer of your property would expect in most cases;

static class Program
{
    static void Main()
    {
        Base baseObject = new Derived();
        Derived derivedObject = new Derived();
        Console.Write(derivedObject.Test());
        Console.Write(baseObject.Test());
        Console.Write(((Base)derivedObject).Test());
    }
}

class Base
{
    public virtual int Test()
    {
        return 1;
    }
}

class Derived : Base
{
    public new int Test()
    {
        return 2;
    }
}
+5
source

For C ++, you can use the scope resolution operator:

Derived d;
d.Base::Method();
+3
source

All Articles