I am going through a book on Design Patterns by GoF - online link.
In this book, in Adapter pattern, in Sample Code section, I have come across this particular code:
class TextView {
public:
TextView();
void GetOrigin(Coord& x, Coord& y) const;
void GetExtent(Coord& width, Coord& height) const;
virtual bool IsEmpty() const;
};
This class TextView
is privately inherited by TextShape
as below:
class TextShape : public Shape, private TextView {
public:
TextShape();
virtual void BoundingBox(
Point& bottomLeft, Point& topRight
) const;
virtual bool IsEmpty() const;
virtual Manipulator* CreateManipulator() const;
};
Then in this void TextShape::BoundingBox
function as below:
void TextShape::BoundingBox (
Point& bottomLeft, Point& topRight
) const {
Coord bottom, left, width, height;
GetOrigin(bottom, left); //How is this possible? these are privately inherited??
GetExtent(width, height); // from textView class??
bottomLeft = Point(bottom, left);
topRight = Point(bottom + height, left + width);
}
As one can see, the functions GetExtent
& GetOrigin
is called TextShape, whereas, the class TextView
containing these was inherited privately.
My understanding is that, in private-inheritance, all the parent class
members become inaccessible, so how is this (void TextShape::BoundingBox()
) function trying to access it?
UPDATE:
Thanks all for answering, I had got into a wrong notion while reading about private inheritance. I felt, it would even prevent access to any of the members, whereas practically it changes the access-specifiers and not accessibility. Thanks you very much for clarifying :)
During private inheritance, the parent members become inaccessible for everyone else, not the class itself! The protected and public members of the parent class are still accessible in the derived class and friends thereof.
Example:
class Base
{
public: int publ;
protected: int prot;
private: int priv;
};
class Derived: private Base
{
friend void g();
void f()
{
priv = 42; //error, priv is private
prot = 42; //OK
publ = 42; //OK
}
};
int main()
{
Derived d;
d.priv = 42; //error
d.prot = 42; //error
d.publ = 42; //error
}
void g()
{
Derived d;
d.priv = 42; //error
d.prot = 42; //OK
d.publ = 42; //OK
}