Andiih
Andiih

Reputation: 12423

how to override a base class method called from a constructor

I'm probably doing this totally wrong..

public class BaseClass
{
  public string result { get; set; }

  public BaseClass(){}
  public BaseClass(string x) {
    result = doThing(x);
  }
  public virtual string doThing(string x)
  {
     return x;
  }
}



public class DerivedClass : BaseClass
{

  public DerivedClass(){}
  public DerivedClass(string x):base(x){}
  public override string doThing(string x)
  {
     return "override" + x;
  }
}

I'd like for a new DerivedClass("test") to have a result of "overridetest" but it doesn't: it calls the base method of doThing. Am I missing something? Do I need to make an AbstractClass and have both BaseClass and DerivedClass inherit from that, Derived class also overriding methods?

Upvotes: 3

Views: 7948

Answers (4)

Saeb Amini
Saeb Amini

Reputation: 24459

You can't access a subclass' instance member from a base class.

It calls the base class's doThing method because that is the only available doThing method as far as the base class is concerned. If you want an instance of each class call it's own doThing method, in your child class replace:

public DerivedClass(string x):base(x){}

with:

public DerivedClass(string x)
{
    doThing(x);
}

Upvotes: 2

Bolu
Bolu

Reputation: 8786

It's because your DerivedClass uses the base constructor and will set result as base.doThing("test") which is "test".

so you could change your DerivedClass to:

public class DerivedClass : BaseClass
{

  public DerivedClass(){}
  public DerivedClass(string x):base(x)
  {
     result="override"+x; 
     //or as result already be set as x, you can use: result="override" + result;
  }

}

or as you said,

need to make an AbstractClass and have both BaseClass and DerivedClass inherit from that, Derived class also overriding methods?

Upvotes: 0

Mark
Mark

Reputation: 1924

From a design perspective, you should always be wary of "doing things" during a constructor call. The purpose of a constructor is merely to get an instance of the class into a valid state for future use; it shouldn't try to "do" anything else or have any other side effects. If your object construction is a complicated affair, you might want to employ the Builder or Factory patterns to shield calling code from the complexity.

Upvotes: 0

edvaldig
edvaldig

Reputation: 2299

The problem is that you are making a virtual call in the constructor. The mechanics of this issue and possible workarounds are detailed here.

In short, the overridden function has not yet been constructed when you enter the constructor of the base class, therefore the virtual function in the base class is called.

Upvotes: 3

Related Questions