Question:
How to change variable value in base class?
anonymous
2012-05-06 03:22:44 UTC
I have a class that derives from a base class. I can access the member of the base class but the derived class treats it as it's own variable. How do I change the value of the base class variable? For example
(C# Example)

class A
{
public int value = 0;

public void Display()
{
Console.WriteLine(value);
}
}

class B : A
{
public void Update()
{
base.value++;
}
}

// Main

{
A aClass = new A();
B bClass = new B();

bClass.Update();
a.Class.Display();
}

// Result = 0. I want the result to be 1. How come I can't directly change the value of the base class?
Three answers:
peteams
2012-05-06 03:44:40 UTC
aClass is an instance of class A.



bClass is an instance of class B, which extends class A.



So you have two instances of class A, one a pure instance called aClass, one the base class for bClass.



When you call bClass.Update() you increment the value inside its base class, not in the separate instance belonging to aClass.



Two ways you could change that behaviour are:



1. Call bClass.Display() rather than aClass.Display()

2. Declare value using "public static int value = 0;", the static keyword says value belongs to the class A itself, not to instance of class A.



The second option is unlikely to be what you want.
anash
2016-12-16 08:35:54 UTC
a is member of Base class. D1 class is baby of Base class, so D1 class promptly have a. it is inheritance. Inheritance works on class individuals no longer on value of people belong to merchandise.
James Bond
2012-05-06 03:30:09 UTC
You have mistaken,

bClass.Display() will give you what you want


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...