Basic OO question


B

bz

Hi,

I have a base class with several constructors and I want to create a
derived class, as below

class MyBase {
public MyBase() {...}
public MyBase(int ID) {...}
public MyBase(string ID_str) {...}
//....
public void Load() {....}
}

class MyDerived: MyBase {
public MyDerived() {....}
}

If I create a variable of type MyDerived, I can access Load method,
which obvious executes the Load from MyBase
However, I cannot create a variable of type MyDerived using other than
default constructor

MyDerived ob1 = new MyDerived(); // compiles ok
MyDerived ob2 = new MyDerived(SomeID);

This later gives me compilation error that there is no constructor
with 1 parameter.

So, the contructors from base class are not inherited, as with other
public methods? Do I have to define in MyDerived all constructors I
want to use, and they'll call the corresponding constructors from
MyBase?

Thanks
 
Ad

Advertisements

C

Chris Mullins [MVP - C#]

bz said:
So, the contructors from base class are not inherited, as with other
public methods?

Correct. Constructors are not inherited.
Do I have to define in MyDerived all constructors I
want to use, and they'll call the corresponding constructors
fromMyBase?

Yup. That's exactly what you need to do.
 
M

Marc Gravell

and they'll call the corresponding constructors from MyBase?

By default they will call the default (base) constuctor. To use
specific constructors, you need to give it more of a clue:

class ClassA {
public ClassA() {
Console.WriteLine("ClassA.ctor()");
}
public ClassA(int x) {
Console.WriteLine("ClassA.ctor(int x)");
}
}
class ClassB : ClassA {
public ClassB() { // uses ClassA.ctor() by default
Console.WriteLine("ClassB.ctor()");
}
public ClassB(int x) : base(x) { // need to be specific
Console.WriteLine("ClassB.ctor(int x)");
}
}
 
G

Guest

bz said:
So, the contructors from base class are not inherited, as with other
public methods? Do I have to define in MyDerived all constructors I
want to use, and they'll call the corresponding constructors from
MyBase?

Yes.

Your IDE should have a "generate constructors from super class".

Note that:
should have != has

Arne
 
Ad

Advertisements

Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top