Link to home
Start Free TrialLog in
Avatar of dineth
dinethFlag for United States of America

asked on

virtual & override keywords

Hi experts !!

Wanna know the point of using virtual keyword for a methods declaration & override keyword in a subclasses implementation for a certain inherited method.


class A
{
    public virtual void methodA()
    {
       Console.WriteLine("base methodA()");
    }
}

class B : A
{
    //override inherited methodA()
    public override void methodA()
    {
        base.methodA();
        Console.WriteLine("sub methodA()");
    }

}

Now tell me itsn't this the same as the above code snippet ?? The only thing I've not done explicit declaration as virtual in base implementation & override in the subclasses implementation.

class A
{
    public void methodA()
    {
       Console.WriteLine("base methodA()");
    }
}

class B : A
{
    public void methodA()
    {
        base.methodA();
        Console.WriteLine("sub methodA()");
    }

}

What's the point of virtual method declaration ??


ThankX
--Din--

Avatar of peterdownes
peterdownes

Since A is the base class of B, you can have an A reference carry a B object:

private A refA;

refA=new B();

refA.MethodA(); // will write sub on virtual method, but base on non-virtual method

The compiler does check at runtime to call the right method, but with non-virtual methods the compiler just assumnes which to call depending on the reference at compile-time. That's the difference.
ASKER CERTIFIED SOLUTION
Avatar of jasonclarke
jasonclarke

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dineth

ASKER

Thanks guys !! thanks for all the help...

--Din--