Jump to content

C# creating constructors for child class (Inheritance)

kaddle

in the book i'm reading it states that there are two ways to create a constructor for the child class. it vaguely implies that the first way is for creating the child constructor is to create a parameter-less constructor and the second way is for creating a non parameter-less constructor, but it's not exactly clear on whether that is absolute. so my questions are about whether these two ways that i will demonstrate are the only ways to create child class constructors and if the parent constructor is always called.

 

the code below is from the exercises that i am following in the book. the book isn't the problem. it's a good book. i just need more information.

 

    class Member
    {
        protected int annualFee;
        private string name;
        private int memberID;
        private int memberSince;

        public override string ToString()
        {
            return "\nName: " + name + "\nMember ID: " + memberID + "\nMember Since: " + memberSince + "\nTotal Annual Fee: " + annualFee;
        }

        public Member()
        {
            Console.WriteLine("Parent Constructor with no parameter");

        }
        public Member(string pName, int pMemberID, int pMemberSince)
        {
            Console.WriteLine("Parent Constructor with 3 parameters");

            name = pName;
            memberID = pMemberID;
            memberSince = pMemberSince;
        }
    }

    class NormalMember : Member
    {
        public NormalMember()
        {
            Console.WriteLine("Child constructor with no parameter");
        }
        public NormalMember(string remarks) : base("jamie", 1, 2015)
        {
            Console.WriteLine("Remarks = {0}", remarks);
        }
    }

so in the code above we have the parent class Member and the child class NormalMember. from what i'm gathering from the book, the two ways to create a child constructor are the two ways displayed in the child class above. the first way is to make a normal constructor without any parameters, and the second way is to use the colon and base keyword.

 

so as for my questions, am i right to assume that the only time the parent class constructor will be called when you create an object for the child class constructor is when you make a parameter-less constructor in the child class, or a non parameter-less constructor in the child class using the colon and base keyword?

 

also, am i allowed to make a non parameter-less constructor in the child class without using the colon and base keyword? like a constructor that won't call parent class constructors when an object is made for it?

Link to comment
Share on other sites

Link to post
Share on other sites

On 10/4/2019 at 9:07 AM, schwellmo92 said:

The only time the parent class ctor will be called is when you use base(). base() can also be used for overridden methods, you can read more here.

That is not correct. You can't create an instance of NormalMember without calling a constructor of its base class. If you do not specify ": base()" then the parameterless constructor is called implicitly. If there is no parameterless constructor in the base class, then you must call "base(...)" with the required argument(s).

 

Example:

public class Program {
    public static void Main() {
        Child child = new Child();
    }
}

public class Parent {
    public Parent() {
        Console.WriteLine("Parent Constructor with no parameter");
    }
}

public class Child : Parent {
    public Child() {
        Console.WriteLine("Child Constructor with no parameter");
    }
}

 

The Child constructor implicitly calls the parent constructor in this case. There is no need to add " : base()". Simply run the program and you should see the output:

Parent Constructor with no parameter
Child Constructor with no parameter

It is not possible to create an instance of Child without calling a base constructor (either implicitly or explicitly), because the base class must be initialized. If Parent does not have a parameterless constructor, then a call to base() is obligatory, because you must provide arguments.

 

This will not compile

public class Parent {
    public Parent(int arg) {
        Console.WriteLine("Parent Constructor with the arg parameter");
    }
}

public class Child : Parent {
    public Child() { // <-- ERROR: There is no argument given that corresponds to the required formal parameter 'arg' of 'Parent.Parent(int)'
        Console.WriteLine("Child Constructor with no parameter");
    }
}

The above example is not legal, because Parent does not have a parameterless constructor. You can't create an instance of Parent without a value for "arg". This also means you can't create an instance of Child without a value for "arg".

 

You have three options:

- Create a parameterless constructor in Parent

- Call base with a hard coded argument

- Add your own constructor that takes an argument and hand it to Parent

public class Child : Parent {
    public Child() : base(1) {
        // Explicit call to base constructor with an argument, which allows Child to have a parameterless constructor
    }
}

 

public class Child : Parent {
    public Child(int arg) : base(arg) {
        // Explicit call to base constructor with an argument from Child's constructor
    }
}

 

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

I think these explanations will make more sense with some context.

It's important to remember the purpose of inheritance.

Generally, a base class is created when some group of objects all share some data (fields) or some actions (methods). The child classes then specialize and extend on the functionality of the base class by adding their own fields or methods specific to their purpose.

By this definition of the purpose of inheritance, it follows easily that the base class constructor must be called, because all child classes are just an extension of the base class, and therefore contain all the members of the base class. In fact, this is the definition of the purpose of inheritance that Microsoft follows: On MSDNs introductory page on inheritance in C# they state:
 

Quote

Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes.

Conceptually, a derived class is a specialization of the base class. For example, if you have a base class Animal, you might have one derived class that is named Mammal and another derived class that is named Reptile. A Mammal is an Animal, and a Reptile is an Animal, but each derived class represents different specializations of the base class.

When you define a class to derive from another class, the derived class implicitly gains all the members of the base class, except for its constructors and finalizers. The derived class can thereby reuse the code in the base class without having to re-implement it. In the derived class, you can add more members. In this manner, the derived class extends the functionality of the base class.

 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×