Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding a function c#

I was just trying to master the concept of virtual function using a console app. I noticed as soon as I override a base class function, return baseclassname.functionname(parameters) gets inserted in my function body automatically. Why does this happen?

class advanc
{
    public virtual int  calc (int a , int b)
    {        
         return (a * b);        
    }        
}

class advn : advanc
{
     public override int calc(int a, int b)
     {
          //automatically inserted
          return base.calc(a, b);
      }        
}
like image 605
Karthik Avatar asked Nov 29 '11 10:11

Karthik


People also ask

Can you override function in C?

To override a function, when compiling its consumer's translation unit, you need to specify that function as weak. That will record that function as weak in the consumer.o . In above example, when compiling the test_target. c , which consumes func2() and func3() , you need to add -include weak_decl.

What is function overriding give example?

Function overriding in C++ is a feature that allows us to use a function in the child class that is already present in its parent class. The child class inherits all the data members, and the member functions present in the parent class.

How do you overwrite a function?

To override a function you must have the same signature in child class. By signature I mean the data type and sequence of parameters. Here we don't have any parameter in the parent function so we didn't use any parameter in the child function.


1 Answers

By overriding a virtual function you expand the functionality of your base class and then call the base class for the 'base functionality'.

If you would remove the 'return base.calc(a,b)' line, the base class code would not execute.

If you want to completely replace the functionality this is not a problem but if you want to extend the functionality then you should also call the base class.

The following code demonstrates this (just put it in a Console Application)

class advanc
{
    public virtual int calc(int a, int b)
    {
        Console.WriteLine("Base function called");
        return (a * b);
    }
}

class advn : advanc
{
    public bool CallBase { get; set; }
    public override int calc(int a, int b)
    {
        Console.WriteLine("Override function called");

        if (CallBase)
        {
            return base.calc(a, b);
        }
        else
        {
            return a / b;
        }
    }
}

private static void Main()
{
    advn a = new advn();

    a.CallBase = true;
    int result = a.calc(10, 2);
    Console.WriteLine(result);

    a.CallBase = false;
    result = a.calc(10, 2);
    Console.WriteLine(result);
    Console.WriteLine("Ready");
    Console.ReadKey();
}
like image 85
Wouter de Kort Avatar answered Oct 08 '22 09:10

Wouter de Kort