Reputation: 24092
I have been programming in C++ for sometime and now I am starting to work with C# but I cannot get the idea of virtual
and override
keywords. Since the pointers and all related to it's stuff is mostly gone from C++ we do not really need them do we ? Or I am missing some major points of C# programming.
Example :
namespace ConsoleApplication1
{
public class Employee
{
public virtual void GetPayCheck()
{
Console.WriteLine("employee gets his pay check ");
}
public void Work()
{
Console.WriteLine("employee works ");
}
}
public class Manager : Employee
{
public override void GetPayCheck()
{
Console.WriteLine("MANAGER gets his pay check ");
}
}
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee();
Manager exec = new Manager();
emp.Work();
exec.Work();
emp.GetPayCheck();
exec.GetPayCheck();
}
}
}
Even if I omit virtual or override keywords ( or both ) I still get the same output. What am I
Upvotes: 1
Views: 1788
Reputation: 42344
Try:
Employee manager = new Manager();
manager.GetPayCheck();
Do you still get the same result either way?
Answer: you don't.
If you use virtual
and override
, Manager
's version of GetPayCheck()
gets called no matter what. If you omit both virtual
and override
, Employee
's version of GetPayCheck()
will get called if your instance is cast to an Employee
, and Manager
's version will get called if your instance is cast to a Manager
. The latter case is called "hiding", and you'll get a compiler warning suggesting you use the new
keyword to make it explicit that the hiding was intentional.
Upvotes: 1
Reputation: 14411
Using virtual
and override
allows you to completely replace the Work
method, regardless of what type the variable is declared as. If a method is declared as virtual, the CLR checks if the object is a derived class and if the method has been overridden. If a method is not virtual, the CLR just calls the method with the name Work
from the type that the object has been declared as.
static void Main(string[] args)
{
Employee emp = new Employee();
Manager exec = new Manager();
DoWork(emp); // employee works and gets pay check
DoWork(exec); // if virtual and override are used, MANAGER get pay check
// however, if you don't override the method, DoWork
// will treat the argument as an Employee.
}
static void DoWork(Employee emp)
{
emp.Work();
emp.GetPayCheck();
}
Upvotes: 6
Reputation: 3951
Even though the pointer syntax is gone, the concepts you learned with C++ pointer and reference variables exist. virtual does the same thing in C# as in C++: it declares a method as replacable in a sub-class. override replaces whether or not the method is virtual, so that is why your code works the way it does.
Upvotes: 2