❔ 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
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
I see, but for the fields part
If my parent class were to have like
And my sub class be:
uhm
Would I not need to rewrite the fields again?
Why?
Ohh I see you're right im stupid
But if it were
do you understand private and protected access modifiers?
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
If it doesnt exist, you need to write a new one, yes
thats kinda reductive
OH ok, I think im starting to understand, tysm for the help
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.