-
Inheritance
i'm in the c++ inheritance lesson in cprogramming.com... In that the syntax for making a class(derived class) inherit all the stuff from another class(base class) is this:
Code:
class base{
//members...
};
class derived : public base{
//members.
};
My Question is, that instead of writing:
Code:
class derived : public base{
//members.
};
if i write:
Code:
class derived : protected base{
//members.
};
or if i write:
Code:
class derived : private base{
//members.
};
What would it mean?
can anybody help me out please?
-
You need to understand principles of object-oriented design to grasp my answer. (Note that different OO methodologies use slightly different languages than I have here).
There are various types of relationships between classes, including "is a" (for example, a Cat is an Animal), "implemented using" relationships (the Submarine class might be "implemented using" a Ship class, noting that a Submarine has a lot of characteristics in common with a Ship, but - depending on point of view - is not always viewed as a Ship), "containment" or "ownership" relationships (e.g. a Garage may contain zero or more Vehicles, a Person may own a Car).
Public inheritance, conventionally, is used to represent "is a" relationships. A public, protected, and private members of base become (respectively) public, protected, and private members of derived.
Protected and private inheritance are conventionally used for "implemented using" relationships. The difference between them is related to further derived classes (e.g. if you use your "derived" as a base class). With protected inheritance, the further derived classes have access to base's public and protected members (but never to private members). With private inheritance, the further derived classes have no access to base members (as they are effectively private members of derived).
Sometimes any of the inheritance types are used to implement "containment" or "ownership" relationships. This is generally considered poor form (as it is better to represent a "A contains a B" relationship as "A has a member of type B", rather than using inheritance at all).