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(){} }
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(){} }
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.
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.
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
.