Inherit base constructor

bondra

Well-known member
Joined
Oct 24, 2020
Messages
77
Programming Experience
Beginner
I've just started to learn inheritence of classes. And upon initializing of an inherrited class I want to pass in the existing fields from the base class.
I've tried to inherit the constructor of the base class but can't get my head around Line 15: base(horsepower, color).

C#:
    class Vehicle
    {
        protected int Horsepower { get; set; }
        protected string Color { get; set; }

        public Vehicle(int horsepower = 0, string color = "")
        {
            Horsepower = horsepower;
            Color = color;
        }     
    }
    class Truck : Vehicle
    {
        private int Load { get; set; }
        public Truck (int load = 0) : base(horsepower, color)
        {
            Load = load;
        }
    }
}

C#:
    class Program
    {
        static void Main(string[] args)
        {
            Vehicle bil = new Vehicle(300, "Blue");
            Truck truck = new Truck();
            // How can I pass in the fields from the base class constructor in the sub class constructor?:
            // Truck truck = new Truck (100, "Red", 200);
            Console.ReadLine();
        }
    }
 
Last edited:
I updated the inherited class. But this can't be the route to go? Misses the whole point of inheritence?

C#:
    class Truck : Vehicle
    {
        private int Load { get; set; }
        public Truck (int horsepower = 0, string color = "", int load = 0) : base(horsepower,color)
        {
            Load = load;
        }
    }
 
No, it doesn't miss the point of inheritance at all. When you create an object you do so by invoking a constructor - a single constructor. How could you possibly create a Truck object and get those values in if the Truck constructor you call doesn't have those arguments? You couldn't. What you have in post #2 is exactly what you do. The fact that what you were doing in post #1 didn't provide an option to get the required values should be demonstration enough of why.

By the way, maybe you are required to use optional parameters for a class but, if not, but does it really make sense to have a vehicle with no horsepower and no colour?
 
Back
Top Bottom