C
C#13mo ago
krixsick

❔ C# Inheritance Topic Question Mostly about base constructors

Hello! I just had some question regarding C# inheritance. So far, I have a few questions regarding on how inheritance works especially, the base constructors. I understand that inheritance is basically making a class a sub-class or child of a base class or parent. Because of this, the sub/child class can access the methods provided in the parent class. For base constructors, I can't really visualize on scenarios of using them effectively and how they function 100%. So far my questions are this: 1. Do the fields inside both classes get shared when a class inherits from another class 2. Using :base in the derived class' constructor makes the base class constructor called first, but why do we want this to happen? I understand that both constructors can take in different parameters and depending on those parameters, the fields will store that information type. But why do we have to initialize the base class if we initialize the derived class (child class) Thanks!
11 Replies
phaseshift
phaseshift13mo ago
1. yes 2. that's how it is conceptually - the derived class is built 'on top' of the base. In a common example of inheritance you get e.g. Dog -> Animal. It is nonsense to have the dog-specific parts initialised but not the animal bits
krixsick
krixsick13mo ago
I see, but for the fields part If my parent class were to have like
private bool isOn
private string brand

public Electrical_Device(bool isOn, string brand)
{
IsOn = isOn;
Brand = brand;
}
private bool isOn
private string brand

public Electrical_Device(bool isOn, string brand)
{
IsOn = isOn;
Brand = brand;
}
And my sub class be:
private bool isOn
private string brand
class TV(bool isOn, string brand)
{
IsOn = isOn;
Brand = brand;
}
private bool isOn
private string brand
class TV(bool isOn, string brand)
{
IsOn = isOn;
Brand = brand;
}
phaseshift
phaseshift13mo ago
uhm
krixsick
krixsick13mo ago
Would I not need to rewrite the fields again?
phaseshift
phaseshift13mo ago
Why?
krixsick
krixsick13mo ago
Ohh I see you're right im stupid But if it were
phaseshift
phaseshift13mo ago
do you understand private and protected access modifiers?
krixsick
krixsick13mo ago
different variables I only understand private and public rn 😅 If it was a different field for the sub class Then I would need to write it If it were the same I wouldn't
phaseshift
phaseshift13mo ago
If it doesnt exist, you need to write a new one, yes thats kinda reductive
krixsick
krixsick13mo ago
OH ok, I think im starting to understand, tysm for the help
Accord
Accord13mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.