Search code examples
c#javaoopcoding-styleconstructor

Purpose of Constructor chaining?


After reading this Constructor chaining question I am just curious to know why would any one do constructor chaining?

Could some one please shed some light on type of scenarios where this might be useful.

Is this a good programming practice?


Solution

  • It's absolutely a good practice for two main reasons:

    To avoid code duplication

    class Foo
    {
        public Foo(String myString, Int32 myInt){
            //Some Initialization stuff here
        }
    
        //Default value for myInt
        public Foo(String myString) : this(myString, 42){}
    
        //Default value for both
        public Foo() : this("The Answer", 42){}
    }
    

    To enforce good encapsulation

    public abstract class Foo
    {
        protected Foo(String someString)
        {
            //Important Stuff Here
        }
    }
    
    public class Bar : Foo
    {
        public Bar(String someString, Int32 myInt): base(someString)
        {
            //Let's the base class do it's thing
            // while extending behavior
        }
    }