How can I call a constructor with a parametric basis for a base class from a derived class if the derived class does not have a parameterized constructor?

I have a base class with two constructors: a default constructor and a parameterized constructor. Another class inherits this base class and only has a default constructor. How can I call the constructor of a parameterized base class from a derived class?

+3
source share
3 answers

It's not entirely clear what your question is, but I suspect that you either want to add an explicit constructor without parameters to your child class:

// Parameterless child constructor calling parameterized base constructor
public Child() : base("foo", "bar") {
}

or add both parameterized and without parameters:

public Child() {
}

public Child(string foo, string bar) : base(foo, bar) {
}

, - , , , . .

.

+8

- ?

class Parent
{
    public Parent(){}
    public Parent(string s) {}
}

class Child : Parent
{
    public Child() : base("42") { }
}
+2

Here you go:

// Parent class
class Parent
{
    public Parent()
        {
        // Paremeterless constructor
        }

        public Parent(string a, int b)
        {
        // Paremterised constructor
        }       
}


// Child class       
class Child : Parent
{
    public Child()
                :base("hi", 10)
        {
        // Parameterized constructor of the base class is invoked   
        }
}
+1
source

Source: https://habr.com/ru/post/1795209/


All Articles