Sign in to follow this  
v0dKA

C# - mixing "private" and "virtual"

Recommended Posts

I just learned that C# does not allow you to have private virtual methods. What's the logic behind this? As an example of where I might need this, consider the following hypothetical code design:
abstract class Actor
{
    public abstract virtual void render();    // Draw the actor
    private abstract virtual System.Drawing.Rectangle getBoundingBox();
}

class Player : Actor
{
    public override void render()
    {
        // Makes calls to getBoundingBox()
        // ...
    }

    private override System.Drawing.Rectangle getBoundingBox()
    {
        // ...
    }
}
In the code example above, render() is public: whoever is in charge of the actor is responsible for drawing it, and therefore should have access to its render() method. However, only the class itself should ever need the bounding box, so getBoundingBox() is declared private. I'm not sure if this is the best example, but still, why is this not allowed? (My guess: because the base class should not, by ideology, enforce its subclasses to handle its internal routines in any particular manner. That is, each derived class itself is responsible for determining how it manages itself. Is this right?)

Share this post


Link to post
Share on other sites
private means that I and only I can access this method. Derived classes do NOT have access to private methods so how could they possibly override them?

protected is the word you're looking for -> I and anyone who derives from me has access to this method. but people outside of us (other classes) do not have access.

-me

Share this post


Link to post
Share on other sites
Quote:
Original post by v0dKA

private abstract virtual System.Drawing.Rectangle getBoundingBox();


-Abstract and virtual must be protected or public.

-Virtual, override, and abstract are mutually exclusive except in one case. The abstract and override modifiers may be used together so that an abstract indexer can override a virtual one.

I think what you're looking for in this case is "protected abstract".

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this