Reputation: 51
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 !
Upvotes: 3
Views: 9898
Reputation: 16698
Try to call the base class constructor this way:
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;
}
}
As per your requirement, you can even call the default constructor instead of parametrized constructor as well.
public Humain(string _Name, int _Age, string _Langue) : base ()
{
Console.WriteLine("Constrcut Humain Called\n");
Name = _Name;
Age = _Age;
Langue = _Langue;
}
Upvotes: 0
Reputation: 67987
public Humain(string _Name, int _Age,string _Langue) : base(_Name, _Age)
{
Lange = _Langue;
}
Upvotes: 1
Reputation: 6678
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.
Upvotes: 1
Reputation: 194
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;
}
};
Upvotes: 6