Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance - Can't access base class data member in derived class

One doubt in inheritance, I have two class named A and B.
A is Base Class and B is Derived Class. B Class inheriting two data members and two member functions of A Class.

In derived class, accessing the static data member is Working but accessing the non static data member gives error. This same case is also for Member Functions. I can't access non static member function.

If i access either static or non static variable | function inside any of derived class function it working fine.

Why i can't access directly in a class. Why its not showing error when i access inside of any derived class function. Any one please clarify my doubts.

reference Image

 class A
{
    protected string msg1;
    protected static string msg2;

    protected  string alert1() {
        return "Welcome";
    }
    protected static string alert2()
    {
        return "Welcome All";
    }
}
class B : A {

    string copyMsg1 = msg1;
    string copyMsg2 = msg2;

    string getMsg1 = alert1();
    string getMsg2 = alert2();

    void display() {
        msg1 = "";
        msg2 = "";
        alert2();           
    }
}
like image 789
Muthuraman Sundararaj Avatar asked Feb 18 '26 06:02

Muthuraman Sundararaj


1 Answers

This line is illegal:

string getMsg1 = alert1();

Because it is equivalent to

string getMsg1 = this.alert1();

and accessing this in a field initializer is illegal. Why? Because field initializers run before either the derived class constructor or the base class constructor, and therefore you could be calling a method that depends on the constructor having already run.

The correct solution is to put your initializations into the constructor:

class B : A {
  string copyMsg1;
  string copyMsg2; 
  string getMsg1;
  string getMsg2;

  public B() 
  {
    this.copyMsg1 = this.msg1;
    this.copyMsg2 = A.msg2; 
    this.getMsg1 = this.alert1();
    this.getMsg2 = A.alert2();
  }

The body of the constructor runs after the field initializers of the derived class, the field initializers of the base class, and the constructor body of the base class. The derived constructor body runs last, and therefore you know that all the stuff it accesses has already been created.

While we're at it: note that methods in C# traditionally begin with a capital letter.

Also, there is not really a good reason shown in this code to do the copying at all. You already have access to the base class members from the derived class, so why are you copying them into the derived class?

like image 128
Eric Lippert Avatar answered Feb 19 '26 19:02

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!