i'm a C++ Programmer,and i'm new in C# i have written a little program to test inheritance so here the source code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lesson3_Class_inherit_
{
public class Personne
{
public string Name;
public int Age;
public Personne() { }
public Personne(string _Name, int _Age)
{
Name = _Name;
Age = _Age;
Console.WriteLine("Constrcut Personne Called\n");
}
~Personne()
{
Console.WriteLine("Destruct Personne Called\n");
}
};
class Humain : Personne
{
public string Langue;
public Humain(string _Name, int _Age,string _Langue)
{
Console.WriteLine("Constrcut Humain Called\n");
Name = _Name;
Age = _Age;
Langue =_Langue;
}
};
class Program
{
static void Main(string[] args)
{
Humain H1 = new Humain("majdi", 28, "Deutsch");
Console.ReadLine();
}
}
}
The output : Construct Humain Called\ and the construct for the class Personne was not called why !!! In C++ the parent class constructor is called first !! Please help !
In C# you must explicitly call a parent constructor by using the base keyword. so Humain would look like
class Humain : Personne
{
public string Langue;
public Humain(string _Name, int _Age,string _Langue) : base(_Name, _Age)
{
Console.WriteLine("Constrcut Humain Called\n");
Name = _Name;
Age = _Age;
Langue =_Langue;
}
};
Because it calls the default constructor. To call the other constructor you need to write:
base(_Name, _Age);
at the beginning of Humain's constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With