views:

77

answers:

3

I want to know if i don't put override key word before the method in derived class method m1(), then what is the default value before this, or will it throw a compile time error?

class A { virtual void m1(){} }
class B: A { void m1(){} }
+7  A: 

First, you'll get a compile-time error because virtual members can not be private which A.m1 is as written.

Second, once you fix this, you'll get a compile-time warning that B.m1 hides the inherited member A.m1.

Third, if you do something like this:

A a = new B();
a.m1();

This will invoke A.m1 whereas if you insert override into the definition of B.m1 then the above will invoke B.m1. However, if you insert new into the definition of B.m1 then the above will still invoke A.m1 but it will omit the compile-time warning.

Jason
it will hide means the base class method will no b inherited to derived class. If i use the new kew then gain it will hide base class method. and if so then what is the difference between using the key word KEY and not using key word KEY
NoviceToDotNet
By "KEY" did you mean `new`? The difference is that it will get rid of the compile-time warning. The warning is there to tell you, "hey, did you mean to override or hide the inherited member? I'm going to assume you meant to hide but you should look into this." The `new` is to tell the compiler, "yes, I meant to hide the inherited member." So yes, the behavior is the same, but the warning serves a real purpose. C# is careful to keep you from shooting yourself in the foot.
Jason
If you want to hide it then use "new" to indicate that you really want to hide and not override it. The only thing new does is suppressing the compiler warning.
CodeInChaos
one thing more sir what does hiding means in OOPs terminology, if possible please give me a good example
NoviceToDotNet
@NoviceToDotNet: See §3.7.1.2 of the C# specification.
Jason
and one more thing i want to know if program generate warning as u told "you'll get a compile-time warning that B.m1 hides the inherited member A.m1." but still if i dot put the override or new key word before the derived class method then still can i execute my program and what will be the default behavior of derived class method will it consider it like with the key word "NEW" or what?
NoviceToDotNet
+1  A: 

When you compile it will give you a warning saying that B.m1() hides inherited member A.m1().

You should use the new keyword if you wish to break the inheritance chain, or use override to get your virtual behavior.

Dismissile
+2  A: 

Without override the compiler issues a warning, as far as I can remember. In this case the method is treated as if it had modifier new.

Vlad