Re: How to hide implementation details?
Immortal Nephi wrote:
I want to create an interface of a door. The client is able to see
the implementation behind the interface because inheritance is
present. The code is stored in the header. How do I hide the
implementation?
Composition.
/* Header Door.h */
class Door
{
public:
Door() {}
virtual ~Door() {}
virtual void Open() {}
virtual void Close() {}
virtual bool IsOpened() { return m_door; }
virtual bool IsClosed() { return !m_door; }
private:
bool m_door;
};
I don't think that in the usual case a Knob is-a Door.
class Knob : public Door
{
public:
Knob() {}
virtual ~Knob() {}
virtual void Lock() {}
virtual void Unlock() {}
virtual bool IsLock() { return m_Knob; }
virtual bool IsUnlocked() { return !m_Knob; }
private:
bool m_Knob;
};
Knob knob;
Door door;
A Door and a Knob that is-a Door, but the instance of Knob, knob isn't
at all related to the instance of Door, door.
door.Close();
knob.Lock();
What I'm really curious about is how you intend to use these classes.
Suppose that:
Door door;
door.Open();
const bool t = door.IsOpened();
What should those lines do if a Door has-a Knob and the Knob::IsLock()
would return true? What value will t have?
I think in someways the question "Should a Door have-a Knob?" is the
similar to "Is an ellipse a circle?" IMHO the best answer is, it depends
on how you want the classes to behave in the program you are creating.
Could your door have a handle instead of a knob? Or would a handle be a
kind of knob? Does the lock have to be part of the knob?
Or maybe you need something like:
class AssembledDoor {
Door door;
Knob knob;
....
};
LR