C
C#2y 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
phaseshift2y 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
krixsickOP2y 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
phaseshift2y ago
uhm
krixsick
krixsickOP2y ago
Would I not need to rewrite the fields again?
phaseshift
phaseshift2y ago
Why?
krixsick
krixsickOP2y ago
Ohh I see you're right im stupid But if it were
phaseshift
phaseshift2y ago
do you understand private and protected access modifiers?
krixsick
krixsickOP2y 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
phaseshift2y ago
If it doesnt exist, you need to write a new one, yes thats kinda reductive
krixsick
krixsickOP2y ago
OH ok, I think im starting to understand, tysm for the help
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server