Kevin Meredith
Kevin Meredith

Reputation: 41939

C# Inheritance Problem

Let's say I have 3 classes:

GrandDad, Dad and Son. Son inherits from Dad, which inherits from GrandDad.

GrandDad has 2 methods:

public virtual void foo();
public virtual void do();

Dad inherits foo(), but overrides do();

public override void do();

If Son wants to modify foo(), is it acceptable to:

make Dad override foo(), but simply call foo.base()? Then Son can override foo(), but Dad's foo() functionality remains the same?

Or is that a hacky way?

Upvotes: 0

Views: 487

Answers (6)

Joel B Fant
Joel B Fant

Reputation: 24766

Dad doesn't have to override foo(). Since Dad simply inherits the version supplied by Granddad (which is still virtual), that means that's what Son gets, too, allowing Son to override foo().

public class Granddad {
    public virtual void foo() {...}
    public virtual void do() {...}
}

public class Dad {
    public override void do() {...}
}

public class Son {
    public override void foo() {...}
}

Upvotes: 2

Steve Wellens
Steve Wellens

Reputation: 20640

The semantics of the problem may have lead you astray.

If you are REALLY doing Father, Son, Grandfather...

You only need one class: Person. It will have a member property called Father that will point to another Person. This way, you can have many generations instead of being locked in at three.

Upvotes: 1

Chris Shain
Chris Shain

Reputation: 51369

Dad doesn't need to override Foo for Son to override Foo. Foo is virtual all the way up the inheritance chain unless someone overrides it AND declares it sealed.

Upvotes: 0

SamStephens
SamStephens

Reputation: 5871

If I've understood your question, there's no need to do anything with Dad. Simply implement foo() within Son.

As Son is a descendant from Dad, nothing within Son changes Dad, so if Son implements foo(), Dad's foo() remains the same, inheriting from GrandDad.

Upvotes: 2

Charles Prakash Dasari
Charles Prakash Dasari

Reputation: 5122

What do you mean by modify foo? If you mean override, then Son can simply override foo(). No need to make Dad override foo() calling base implementation.

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245489

As long as Dad never defined a foo(), there's no reason he has to do anything. Son should be able to override foo() from GrandDad.

Upvotes: 3

Related Questions