C# Programming - Inheritance - Discussion

Discussion Forum : Inheritance - General Questions (Q.No. 6)
6.
What will be the output of the C#.NET code snippet given below?
namespace IndiabixConsoleApplication
{ 
    class Baseclass
    { 
        public void fun()
        { 
            Console.Write("Base class" + " ");
        } 
    } 
    class Derived1: Baseclass
    { 
        new void fun()
        {
            Console.Write("Derived1 class" + " "); 
        } 
    } 
    class Derived2: Derived1
    { 
        new void fun()
        { 
            Console.Write("Derived2 class" + " ");
        }
    }
    class Program
    { 
        public static void Main(string[ ] args)
        { 
            Derived2 d = new Derived2(); 
            d.fun(); 
        } 
    } 
}
Base class
Derived1 class
Derived2 class
Base class Derived1 class
Base class Derived1 class Derived2 class
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
28 comments Page 2 of 3.

Hemant Jakkani said:   1 decade ago
Default access modifiers for member function of class is private.

Since no access modifiers is specified in derived class, it is private, So it is not accessible, so base class method will be called.

Vidit Tyagi said:   1 decade ago
We need to use virtual keyword in base then we can hide the functionality of base class method with the help of new keyword :).

Rajat said:   1 decade ago
Here the new keyword means derived class is calling the hidden function of base class.

Ipsita said:   1 decade ago
What is new here?

Amit said:   1 decade ago
Functions of class Derived1 and Derived2 are inaccessible due to its protection level i.e private (default access specifier) so it will access the function of Base Class because its public.

Vapandian said:   1 decade ago
This is simple. Because other func() are not having public, only base class having public func() ; so this is only executed. If you provide public to derived 2 it will execute.

Srinivas said:   1 decade ago
When ever if you have same method name in the parent (base) class and derived class, if you create an object for derived class then base class will be executed. If we want to execute both the methods to be executed we want to use 'virtual' key word in the base class and 'override key word in the derived class method.

Public virtual void fun1() in base class.

Public override void fun1() in derived class.

Mihi said:   1 decade ago
Since in derived classes for functions no access specifiers specified so those will not inherit. The final method that should inherit is Base class fun(). The output is "Base class"

Api said:   1 decade ago
Thanks chandrashekar.

Harsh said:   1 decade ago
Default access modifiers for member function of class is private.

Since no access modifiers is specified in derive class, it is private.

So it is accesible, so base class method will be called.


Post your comments here:

Your comments will be displayed after verification.