简体   繁体   中英

How to call base class constructor alone through derived class object in c#?

I got the following question during an interview: "how can you call base class constructor (default constructor) alone from derived class object". That object should not call derived class default constructor. How is it possible?

This is the code:

class a
{
    public a()
    {
        MessageBox.Show("Base class called");
    }    
}
class b : a 
{
    public b()
    {
        MessageBox.Show("Derived class");
    }
}

I just want to display base class constructor without the one from derived class being invoked. How can I achieve this?

The way the question is worded sounds like a riddle, but I'd assume it means 'how do you call the base class default constructor from a derived class's non-default constructor'.

This will implicitly happen anyway, but if you want to be explicit you're looking for the base keyword to specify which constructor to call in the base class:

public Derived(object param) : base()
{

}

The only way to not call the derived class's default constructor is to have a non-default constructor in the derived class and instantiate the object using that.

See this fiddle for a demo containing both default and non-default constructors.

Assuming you have the following classes:

class Base 
{
    public Base() { }
}    

class Derived : Base
{
    public Derived() { }   
}

The base -class´-constructor is automatically invoked when creating the derived one. Therefor it is not possible at all to call the base-class constructor without calling the derived-class one. Only way is create an instance of type Base instead of Derived , if you create a Derived its constructor surely is called.

However if you have a second constrcutor within Derived which directly calls the Base -one you may of course bypass the defaulöt-constructor of your derived class:

class Derived : Base
{
    public Derived() { }   
    public Derived(params object[] args) : base() { }   
}

Now you can make the following calls:

Derived d = new Derived(); // will call both default-constructors
Derived d1 = new Derived(null); // calls the params-overloaded constructor and not its default one

Try this code::

class Base 
{
    public Base() {
        Console.WriteLine("BaseClass Const.");
    }
}    

class Derived : Base
{
    public Derived() { }   
    public Derived(params object[] args) : base() { } 
}

    public class Program
    {
        public static void Main(string[] args)
        {

            Derived d = new Derived(null) ;

        }
    }

Expected output :

BaseClass Const.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM