Silly question

janderson askme at me.com
Thu Apr 24 08:36:52 PDT 2008


Jarrett Billingsley wrote:
> "janderson" <askme at me.com> wrote in message 
> news:fuorvl$2j02$1 at digitalmars.com...
> 
>> They are however in my book this is plain wrong.  The whole purpose of 
>> being able to hide abstraction layers is broken.  I should be able to 
>> protect inherited functions from objects that work on that level.  Its a 
>> fundamental principle in C++.
> 
> What?
> 
> Am I the only one who can't understand what this post means? 
> 
> 


I have a interface:
(I'm using C++ because this won't work in D)

class OnRenderI
{
    public:
	virtual void OnRender() = 0;
};


I have a derived class:

class A : OnRenderI
{
    public:
	A() {  GetRender().Add(Me); }
    private:  //Or protected
	virtual void OnRender(); //This is good private
}



I have my render:

class Render
{
    Add(OnRenderI& render);
};


This is very good practice.  The renderer is the one who knows about how 
to render OnRender-ables.  People who have a class A should not be-able 
to call OnRender.  Reasons if they where to use a public on A:

1) Then they are coupling OnRender method to class A.  This is bad 
because not we can't simply remove OnRender and put it elsewhere.

2) The size of A's interface is larger.  That makes the class more 
complex.   You want to keep your interfaces small.  You want to keep the 
responsibility of a class small.  This makes it easier to validate and 
prevent problems.  Essentially you want to make invariants.  Private 
virtual inheritance is tool to help meet those goals.

3) You want to force behavior to occur at the interface level so that 
you can easily switch the owner class without touching how the inherited 
classes work.  It makes it more difficult for you or others from passing 
around A objects instead of OnRender objects to get at the OnRenderI 
method.  Basically its good decoupling.  Stuff that deal with OnRender 
know about OnRender stuff but not A.  Stuff that deal with A know about 
A stuff but shouldn't know about OnRender.

Remember inheritance is one of the tightest couplings there is.  So 
anything that we can do to remove the coupling is a great improvement.

You might want to read, Effective C++ for more information.

Some people even recommend never having a public virtual at all (even in 
the base class).  I won't go that far, but they do have a good point.

I hope that was helpful.
-Joel


More information about the Digitalmars-d-learn mailing list