In C#, a virtual method of base class can be either overridden or hidden by its derived classes, e.g.
using System;
class A {
public virtual void M() {
System.Console.WriteLine("A");
}
}
class B: A {
public override void M() {
System.Console.WriteLine("B");
}
}
class C: A {
public new void M() {
System.Console.WriteLine("C");
}
}
class P {
static void Main(string[] args) {
A b = new B();
b.M();
A a = new C();
a.M();
}
}
Output:
B
A
How about in C++? Only overridable?
[Update for C++11]
Since C++11, you can use the
overridekeyword to tell the compiler that you’re intending to override the base class virtual function.If there is no override keyword but the base class contains a virtual function with the same* signature, then the function is still overriden. Otherwise, hidden.
[Original answer for C++03]
Of course, you can both override and hide a virtual function in C++. You just aren’t very explicit about it (not in C++03 anyway).
example
If the signature coincides with the Base virtual method* then it’s overriding. Otherwise it’s hiding.
So sometimes you accidentally forget a
constand end up hiding the function instead of overriding it. The C++11 override attribute is called to solve this problem. If you use this override attribute but the signatures are incompatible, you will get a compiler error.*(or differs only in that the return types are pointers or references to a Base class and a publicly Derived class respectively)