glasswizzard
Well-known member
- Joined
- Nov 22, 2019
- Messages
- 126
- Programming Experience
- Beginner
I must be misunderstanding inheritance because I want to do a simple thing but it doesn't work. Let's say I have a base class like so:
Now let's say I envision the use for a class like so:
It's the same class but with one extra variable. From what I've learned of inheritance this seems to be the perfect situation to use it. The second class can inherit from the first and just add that one new variable right? The way I tried to do it (which does not work) was like so:
That inherited class doesn't seem to know it has the variables from the old class and says they don't exist in this context.
So am I doing something wrong? Do I not understand how/why inheritance is used?
C#:
public class BaseClass
{
int num1 = 0;
int num2 = 0;
int num3 = 0;
public BaseClass(int a, int b, int c)
{
num1 = a;
num2 = b;
num3 = c;
}
public int Calculate()
{
return num1+num2+num3;
}
}
Now let's say I envision the use for a class like so:
C#:
public class NewClass
{
int num1 = 0;
int num2 = 0;
int num3 = 0;
int num4 = 0;
public NewClass(int a, int b, int c, int d)
{
num1 = a;
num2 = b;
num3 = c;
num4 = d;
}
public int Calculate()
{
return num1 + num2 + num3 + num4;
}
}
It's the same class but with one extra variable. From what I've learned of inheritance this seems to be the perfect situation to use it. The second class can inherit from the first and just add that one new variable right? The way I tried to do it (which does not work) was like so:
C#:
public class NewClass : BaseClass
{
int num4 = 0;
public NewClass(int a, int b, int c, int d)
{
num1 = a;
num2 = b;
num3 = c;
num4 = d;
}
public int Calculate()
{
return num1+num2+num3+num4;
}
}
That inherited class doesn't seem to know it has the variables from the old class and says they don't exist in this context.
So am I doing something wrong? Do I not understand how/why inheritance is used?
Last edited: