I was going over some sample questions for an upcoming test, and this question is totally confusing me.
Consider the following code:
class GraduateStudent : public Student
{
...
};
If the word “public” is omitted, GraduateStudent uses private inheritance, which means which of the following?
-
GraduateStudentobjects may not use methods ofStudent. -
GraduateStudentdoes not have access to private objects ofStudent. -
No method of
GraduateStudentmay call a method ofStudent. -
Only
constmethods ofGraduateStudentcan call methods ofStudent.
Although this is a bare homework-ish question, I’m going to answer it because it is a terrible question. I would almost consider it a trick question, and it doesn’t really make for a good test of knowledge.
The answer is 2. GraduateStudent does not have access to private objects of Student., except that this has nothing at all to do with private inheritance. Point 2 would be true whether or not the
publickeyword were present, since derived classes never have access to the private members of their base classes, no matter how they inherit.Private inheritance means essentially two things (as opposed to public inheritance):
All public methods of
Studentbecome private methods inGraduateStudent. That means that if, for example,Studenthas a public methodfoo(), thenGraduateStudenthas a private methodfoo().The base class is “inaccessible”, which means that polymorphism does not work. In layman’s terms, this means that if
GraduateStudentinherits privately fromStudent, then you cannot treat aGraduateStudent*as if it were aStudent*(or aGraduateStudent&as if it were aStudent&).It’s possible that the author of the question also meant for point 1 to be a correct answer, but it is ambiguously worded. What does it mean that “
GraduateStudentobjects may not use methods ofStudent“? It’s possible that the intent is for this to mean that you cannot call methods inherited fromStudenton objects of typeGraduateStudent, like I wrote in the first point above, but theGraduateStudentobject itself, within its methods, can use methods ofStudent.For example: