Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# inheritance constructor child and parent ??

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 !

like image 471
satyres Avatar asked Nov 26 '25 15:11

satyres


2 Answers

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;
        }



    };
like image 133
PrimeNerd Avatar answered Nov 29 '25 04:11

PrimeNerd


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.

like image 38
user1610015 Avatar answered Nov 29 '25 05:11

user1610015



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!