Inheritance & Member Functions

Inheritance & Member Functions


What ever we discussed for data members are valid for member functions also. A derived class member function can call the base class member function by using the base operator. It is possible to hide the implementation of a Base class member function inside a Derived class by using the new operator. When we declare a method in the Derived class with exactly same name and signature of a Base class method, it is known as method hiding'. But during the compilation time, the compiler will generate a warning. But during run-time the objects of the Derived class will always call the Derived class version of the method. By declaring the derived class method as new, it is possible to suppress the compiler warning.

using System; 
class Base 
{ 
public void Method() 
{ 
Console.WriteLine("Base Method"); 
} 
} 
class Derived : Base 
{ 
public void Method() 
{ 
Console.WriteLine("Derived Method"); 
} 
} 
class MyClient 
{ 
public static void Main() 
{ 
Derived d1 = new Derived(); 
d1.Method(); // displays 'Derived Method' 
} 
}   


Uses of new and base operators are given in the following program.

using System; 
class Base 
{ 
public void Method() 
{ 
Console.WriteLine("Base Method"); 
} 
} 
class Derived : Base 
{ 
public new void Method() 
{ 
Console.WriteLine("Derived Method"); 
base.Method(); 
} 
} 
class MyClient 
{ 
public static void Main() 
{ 
Derived d1 = new Derived(); 
d1.Method(); // displays 'Derived Method' followed by 'Base Method'  
} 
}   
Category: , 0 comments

Leave a comment