A class can be derived from an existing class using the general form:
class class name:(public| protected| private) base class {
member declarations
};
- Visibility of Inherited members:
One aspect of the derived class is the visibility of its inherited members. The access specifier keywords public, protected, and private are used to specify how the base class members are to be accessible to the derived class. The new keyword protected specifies that a member is accessible to other member functions within its own class and any class immediately derived from the member function's class. When you declare a derived class without a base class access specifier, the derivation is considered private. When a base class is declared private, its public and protected members are considered private members of the derived class, while private functions of the base class are inaccessible to any derived class.
Consider developing a class to represent students at a college or university:
enum year { fresh, soph, junior, senior, grad };
class student {
public:
student(char* nm, int id, double g, year x);
void print() const;
protected:
int student_id;
double gpa;
year y;
char name[30];
};
We could write a program that lets the registrar track such students.
While the information stored in student objects is adequate for undergraduates, it omits crucial information needed to track graduate students.
Such additional information might include the graduate students' means of support, department affiliations, and thesis topics.
Inheritance lets us derive a suitable grad_student class from the base class student as follows:
The private access specifier gives you control over how a potential derived class could interact with your class. I recommend that you make all your data members private by default. You can provide public getters and setters if you want to allow anyone to access those data members, and you can provide protected getters and setters if you only want derived classes to access them. The reason to make data members private by default is that this provides the highest level of encapsulation. This means that you can change how you represent your data while keeping the public and protected interface unchanged. Without giving direct access to data members, you can also easily add checks on the input data in your public and protected setters. Methods should also be private by default.
Only make those methods public that are designed to be public, and make methods protected if you only want derived classes to have access to them.
enum support { ta, ra, fellowship, other };
class grad_student : public student {
public:
grad_student
(char* nm, int id, double g, year x, support t,
char* d, char* th);
void print() const;
protected:
support s;
char dept[10];
char thesis[80];
};