Alright, so here’s the exercise:
You must define three classes. One class named MyNum that contains a variable of type int. Second class called MyString, will be derived from MyNum and contains string. Third-class call MyType and returns a variable of type MyNum. Each class will be set to a constructor function and virtual function called Show. The constructor function of MyType receive a MyNum variable, whereas the function Show of MyType will run the Show function of MyNum.
Now, you need set two objects of type MyType and initialize them. Once an object type MyNum and once an object of type MyString.
Here’s the code:
class MyNum
{
protected int num;
public MyNum(int num)
{
this.num = num;
}
public virtual void Show()
{
Console.WriteLine("The number is : " + num);
}
}
class MyString : MyNum
{
string str;
public MyString(string str)
{
this.str= str;
}
}
class MyType : MyNum
{
MyNum num2;
public MyType(MyNum num)
{
this.num2 = num;
}
public override void Show()
{
base.Show();
}
}
class Program
{
static void Main(string[] args)
{
}
}
I’m having the following error:
Error 1 ‘ConsoleApplication1.MyNum’ does not contain a constructor that takes ‘0’ arguments C:\Users\x\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 23 16 ConsoleApplication1
Anyone knows why am I having this error? Thanks.
Since your class subclasses
MyNum, it needs to be able to construct it. You don’t have a default constructor, so you have to explicitly call it with a value.For example:
The class
MyStringwill need similar treatment. It will have to have a constructor that calls the base class constructor, too.Note that, if the
MyNumclass had a default constructor (which could beprotected), this wouldn’t matter. Instead of calling these constructors, the other alternative is to do something like:Edit in response to comments:
If you want to override the base class constructor, try: